質問するログイン新規登録

質問編集履歴

1

テストしたマルチスレッドのコードを追記しました。

2021/08/09 23:34

投稿

ysyk77
ysyk77

スコア4

title CHANGED
File without changes
body CHANGED
@@ -71,4 +71,110 @@
71
71
  ```
72
72
 
73
73
  ### 試したこと
74
- マルチスレッドをWEB上の情報を参考に試しましたが、うまく行きませんでした。
74
+ マルチスレッドをWEB上の情報を参考に試しましたが、うまく行きませんでした。
75
+ マルチスレッド化したときのコードです。
76
+ cameraボタンを押しcaptureを開始すると、黒画面が出力し、ハングアップしてしまいます。
77
+ ```python
78
+
79
+ #!/usr/bin/python3
80
+ # -*- coding: utf8 -*-
81
+ import tkinter
82
+ import cv2
83
+ import threading
84
+ import time
85
+
86
+ stopflag = 0
87
+
88
+ # Thread Test → OK
89
+ class ThreadJob(threading.Thread):
90
+ def __init__(self, v=""):
91
+ threading.Thread.__init__(self)
92
+
93
+ def run(self):
94
+ global stopflag
95
+
96
+ while not(stopflag):
97
+ print('hello,stop=',stopflag)
98
+ time.sleep(1)
99
+ if stopflag != 0:
100
+ break
101
+
102
+ # camera capture
103
+ class ThreadJob2(threading.Thread):
104
+ def __init__(self, v=""):
105
+ threading.Thread.__init__(self)
106
+
107
+ def run(self):
108
+ global stopflag
109
+ cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
110
+ if cap.isOpened() == False:
111
+ return
112
+
113
+ while not(stopflag):
114
+ ret, frame = cap.read()
115
+ name = "video"
116
+ cv2.namedWindow(name, cv2.WINDOW_NORMAL)
117
+ cv2.imshow(name,frame)
118
+ if stopflag != 0:
119
+ break
120
+
121
+ cap.release()
122
+ cv2.destroyAllWindows()
123
+
124
+
125
+ class Application(tkinter.Frame):
126
+
127
+ def __init__(self, master=None):
128
+ super().__init__(master)
129
+ self.pack()
130
+ self.create_widgets()
131
+
132
+ def create_widgets(self):
133
+ # capture
134
+ self.button = tkinter.Button(self)
135
+ self.button["text"] = u"Camera"
136
+ self.button["command"] = self.button_func
137
+ self.button["width"] = 20
138
+ self.button.pack()
139
+
140
+ # stop
141
+ self.btnStop = tkinter.Button(self)
142
+ self.btnStop["text"] = u"Stop"
143
+ self.btnStop["command"] = self.button_Stop
144
+ self.btnStop["width"] = 20
145
+ self.btnStop.pack()
146
+
147
+ # Quit
148
+ self.quit = tkinter.Button(self)
149
+ self.quit["text"] = u"Quit"
150
+ self.quit["width"] = 20
151
+ self.quit["command"] = self.master.destroy
152
+ self.quit.pack()
153
+
154
+ # Callbacks
155
+ def button_func(self):
156
+ global stopflag
157
+ stopflag = 0
158
+ #t = ThreadJob() # スレッド確認OK
159
+ t = ThreadJob2() # capture
160
+ t.start() # スレッドを実行
161
+
162
+ def button_Stop(self):
163
+ global stopflag
164
+ print('stop')
165
+ stopflag = 1
166
+
167
+
168
+ # メイン関数
169
+ def main():
170
+ # Windowの生成
171
+ root = tkinter.Tk()
172
+ root.geometry("200x100")
173
+ root.title(u"basic1")
174
+ app = Application(master=root)
175
+ app.mainloop()
176
+
177
+ if __name__ == '__main__':
178
+ main()
179
+
180
+ ```