Cv2.imshow() freeze

  • OpenCV => opencv_python-4.6.0.66
  • Operating System / Platform => win10
  • Compiler => python
Detailed description

Function cv2.imshow() freezes. The frame to be shown is grabbed by webcam and in debug mode really read. When I step over to cv2.imshow(), the running can never stop. The corresponding window is always gray and has no responding. Since I got it in first iteration and the print(0) code just below imshow is never executed. I think it should be a bug instead of my programming error, but not sure. And I succeeded several times before this situation came, but after that, totally fail as I described. A reinstallation of the library has no use My codes below.

Steps to reproduce
import time
import cv2
import matplotlib.pyplot as plt
import pytesseract
import re

import threading

from datetime import datetime




# Adding custom options
custom_config = r'--oem 3 --psm 6'


cap1 = cv2.VideoCapture(1)
cap2 = cv2.VideoCapture(2)

class camThread(threading.Thread):

    def __init__(self,cap,csv_name,win_name,plot_name,plot,fig) -> None:
        super().__init__()
        self.cap = cap
        self.csv_name = csv_name
        self.win_name = win_name
        self.plot_name = plot_name
        self.plot = plot
        self.fig = fig

    def run(self):
        start = time.time()
        video_name = self.win_name +'_' + datetime.now().strftime("%y-%m-%d_%H;%M") + '.mp4'
        fps = int(self.cap.get(cv2.CAP_PROP_FPS))
        width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        #wr = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'mp4v'), 15, (640,480))
        temp = []
        stamp = []
        cv2.namedWindow(self.win_name,cv2.WINDOW_AUTOSIZE)
        # cv2.waitKey(0), no effect
        with open(self.csv_name,'w') as file:
            while(True):
                ret, frame = self.cap.read()
                if not ret:
                    print('not read')
                    continue
                print('read')
                cv2.imshow(self.win_name,frame)
                print(0)
                frame = frame[20:100,20:150,:]
                t = time.time() - start
                s = pytesseract.image_to_string(frame, config=custom_config)
                try:
                    s = float(re.findall('[0-9]+.[0-9]+',s)[-1])
                except:
                    print(re.findall('[0-9]+.[0-9]+',s))
                    continue
                file.write(f'{t},{s}\n')
                temp.append(s)
                stamp.append(t)
                #wr.write(frame)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
        
        self.plot.plot(stamp,temp)
        self.plot.set_xlabel('relative time /s')
        self.plot.set_ylabel('temperature /°C')
        self.plot.set_title('temperature profile')
        self.cap.release()
        #wr.release()


fig, ax = plt.subplots(2)

thread1 = camThread(cap1,'data1.csv','cam1','plot1.jpg',ax[0],fig)
thread2 = camThread(cap2,'data2.csv','cam2','plot2.jpg',ax[1],fig)
thread1.start()
thread2.start()

fig.savefig('plot.jpg')

cv2.destroyAllWindows()
#cv2.waitKey(1), no effect

yeah don’t call any GUI stuff from spawned threads. make sure all the GUI stuff is done in the main thread. GUI toolkits can be particular about that.

use communication primitives such as queues, or maybe even more basic primitives (semaphores, events, conditions, whatever’s there)

2 Likes

Okay, thanks. That has solved the problem.