개발자 입장에서 스크립트 실행은 명령어 하나로 뚝딱! 할 수 있으니 쉽지만
일반 사람들이 사용하기 위해선 GUI가 필요하다. 많이 요구하는 부분이기도 하고...
('마우스 드래그가 모에요??' 하는 사람도 있었다.)
Python에서 GUI 제작으로 PyQt도 있고 Tkinter 라는 것도 있는 데
이 중에서 Tkinter을 이용하여 비디오를 재생하는 창을 만들어 보자.
나는 GUI 개발 경험이라고는 안드로이드 앱 만들때 잠깐 해본게 다라서 Python에서도 마우스로
쓱쓱 가져오면 알아서 만들어주는 줄 알았따...
https://solarianprogrammer.com/2018/04/21/python-opencv-show-video-tkinter-window/
Python OpenCV - show a video in a Tkinter window | Solarian Programmer
Disclaimer: All data and information provided on this site is for informational purposes only. solarianprogrammer.com makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not
solarianprogrammer.com
위 링크를 참고하면 웹캠을 통해 받은 영상을 창에서 출력하는 방법과 간단한 스냅샷 만들기 등을 가르쳐준다.
하지만 내가 필요한 것은 이게 아니다.
로컬 파일로 비디오 파일을 열고 해당 영상에 머신러닝 알고리즘을 적용한 후 최종 결과를 GUI 창에 뿌리고 싶다.
(위 링크에서 바로 결과 frame을 집어넣으면 화면이 나오지 않을 것이다.)
여러가지를 시도해본 결과 GUI 생성하는 알고리즘 하나와 머신러닝 알고리즘 하나를 Thread로 따로 돌려줘야한다.
다행히 Python Thread는 쉽다!
import tensorflow as tf
import cv2 # OpenCV
import tkinter # Tkinter 및 GUI 관련
import tkinter.ttk
import PIL.Image, PIL.ImageTk
import threading # Thread
result_img = 0 # 전역변수로 최종 이미지를 받도록 했다
class App(threading.Thread):
def __init__(self, window, window_title):
threading.Thread.__init__(self)
self.window = window
self.window.title(window_title)
self.delay = 15
# View Video
self.canvas = tkinter.Canvas(window, width=608, height=480)
self.canvas.pack()
self.update()
self.window.mainloop()
def update(self):
try:
vid = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(vid))
self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
except:
pass
self.window.after(self.delay, self.update)
def main():
global result_img
vid = cv2.VideoCapture(video) # 비디오 받음
video_frame_cnt = int(vid.get(7))
with tf.Session() as sess: # Session은 여기서 열자
# Session Open
for i in range(video_frame_cnt):
ret, img_ori = vid.read()
# 영상에서 객체 검출이나 다른 알고리즘 등등...
result_img = cv2.resize(img_ori, (640, 480)) # 결과 이미지를 넘겨주자
vid.release()
if __name__ == "__main__":
t1 = threading.Thread(target=main, args = ())
t1.daemon = True
t1.start()
t2 = App(tkinter.Tk(), "GUI")
t2.daemon = True
t2.start()
# daemon은 App이 종료되면 다른 스레드도 같이 종료하라고...
나는 YOLOV3 객체 검출 결과를 GUI 창에 표시하기 위해 Session 여는 부분이 있지만 필요 없으면 없애면 된다.
'전체보기 > Python' 카테고리의 다른 글
[Tkinter] Python 폴더 선택 창 생성 (1) | 2020.04.30 |
---|---|
pytesseract 에러 + tesseract-ocr-kor (0) | 2020.02.10 |
임시저장 (0) | 2020.01.08 |
파이썬 GUI (0) | 2019.12.02 |
댓글