Python OpenCV线程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python OpenCV线程相关的知识,希望对你有一定的参考价值。

Python脚本从套接字读取png图像,然后尝试使用OpenCV显示慢速视频。有两个类server.py和Worker.py。 Server.py从套接字接收原始png并将其放在队列中。在自己的线程中,工作人员将png出列并显示它。只有第一张图像正确显示。其他图像不是可见的(即第一个图像保留),但调用ShowImage和WaitKey。

线程模型是对的吗?似乎服务器套接字线程阻止OpenCV线程显示。有没有办法将服务器套接字放在后台线程上?从后台线程调用ShowWIndow和WaitKey是否正确?我对Mac上的Python或OpenCV线程知之甚少。任何意见和建议将不胜感激。

server.朋友:

#! /usr/bin/env python
import sys
import SocketServer
import socket
import subprocess
import time
import cv
import Worker
import ShowImage

HOST = 'andrew-rosenblums-macbook-pro.local'
PORT = 3001
FRAME_SIZE = 144*192
data = ''
worker = Worker.Worker()

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    imagesSaved = 0

    "One instance per connection.  Override handle(self) to customize action."
    def handle(self):
        # self.request is the client connection
        print "connection received.."
        while True:
            #print "calling rcv"
            messageLength = self.request.recv(6)  # Read 6 ascii char image size
            cv.WaitKey(30)
            if (len(messageLength) > 0):
                print "messageLength=" + messageLength
                iLength = int(messageLength)
                message = ''
                while (iLength > 0):
                    if (iLength > 1024):
                        chunk = self.request.recv(1024)
                    else:
                        chunk = self.request.recv(iLength)
                    iLength -= len(chunk)
                    message += chunk
                print "rcvd imsg of len=" + str(len(message))
                worker.write(message)

                if (SingleTCPHandler.imagesSaved == 0):
                    SingleTCPHandler.imagesSaved += 1

        print "closing stream"
        self.request.close()
        print "done receiving"

    def finish(self):
        print "finish called"

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    # Ctrl-C will cleanly kill all spawned threads
    daemon_threads = True
    # much faster rebinding
    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

if __name__ == "__main__":
    server = SimpleServer((HOST, PORT), SingleTCPHandler)
    # terminate with Ctrl-C
    try:
        print "waiting for connections..."
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

worker.朋友

#! /usr/bin/env python
import time
from threading import Thread
from Queue import Queue
import sys
import cv
import cv2
import numpy as np
import Image
from cStringIO import StringIO

class Worker(Thread):

    count = 0

    def __init__(self):
        Thread.__init__(self)

        self.cvImage = None
        cv.NamedWindow('display')
        cv.MoveWindow('display', 10, 10)

        self.queue = Queue()
        self.writer = None
        # Daemon threads won't prevent process from exiting
        self.setDaemon(True)

        # Start ourselves automatically
        self.start()
        print "Worker started"

    def run(self):
        writer = None
        while 1:
            frame = None

            try:
                #frame = self.queue.get(block=False)
                frame = self.queue.get()
                print "display izeof rawImage=" + str(len(frame))

               #convert to mat
                pilImage = Image.open(StringIO(frame));#.convert("RGB");

                bgrImage = np.array(pilImage)

                cvBgrImage = cv.fromarray(bgrImage)
                self.cvImage = cv.CreateImage(cv.GetSize(cvBgrImage),8,3)
                cv.CvtColor(cvBgrImage, self.cvImage, cv.CV_BGR2RGB)

                #show it
                cv.ShowImage('display', self.cvImage)
                cv.WaitKey(30)
                self.cvImage = None
            except:
                frame = None

        print "done with thread"

    # Requests from main thread
    def write(self, frame):
        self.queue.put(frame)

    def stop(self):
        self.queue.put(None)
答案

答案很简单:OpenCV的ShowImageWaitKey必须在主线程中。我猜这是GUI线程。 ServerSockets被推送到自己的线程,这在Python中非常容易。

您只需要:

UDPThread = Thread(target = UDPServer.run)
s.start(UPDThread)

以上是关于Python OpenCV线程的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV 和 Python 多线程 - 在 VideoCapture 对象中搜索

opencv python 多线程视频捕获

Python OpenCV线程

python小白学习记录 多线程爬取ts片段

手把手:使用OpenCV进行面部合成— C++ / Python

python 简单线程和 - OPENCV-示例