Real time plotting of average hue taken from webcam

66 views
Skip to first unread message

siemovit

unread,
Aug 22, 2017, 12:48:35 PM8/22/17
to pyqtgraph
Hello,

I am new in Python and working on a project where I need to display in real time the average hue a picture taken by a camera. For the moment, I use my webcam, for simplicity reasons. I have read many articles and topics, especially http://forum.arduino.cc/index.php?topic=137635.15;wap2 and https://groups.google.com/d/msg/pyqtgraph/haiJsGhxTaQ/sTtMa195dHsJ and my code comes directly from these examples. However, for some reason, the graph doesn't want to plot. 

As I said, I am very beginner and I don't understand exactly what I am doing with the threads, but I have to use it and not the timer approach because the final camera will need such implementation. 

Here is the code I have :

########################

import cv2
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import time
import sys

cap = cv2.VideoCapture(0)
frames = 10
app = QtGui.QApplication([])
average_hue_array = np.empty(frames)

win = pg.GraphicsWindow()
win.setWindowTitle('Real time plotting of the average hue of an image')
p1 = win.addPlot()
plt = pg.plot()

def update(average_hue_array):
    plt.plot(average_hue_array, clear=True)
    
class Reader(pg.QtCore.QThread):
    
    newData = pg.QtCore.Signal(object)
    
    def run(self):
        
        for i in range(0,frames):
            global avghue
            # Take each frame
            _, frame = cap.read()

            # Convert BGR to HSV
            imghsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            average_color_per_row = np.average(imghsv, axis=0)
            average_color = np.average(average_color_per_row, axis=0)
            avghue = average_color.item(0)
            average_hue_array[i] = avghue

            self.newData.emit(average_hue_array)
            time.sleep(0.05)

            print("average hue = {}".format(avghue))
                  
            k = cv2.waitKey(1) & 0xFF
                  
            if k == 27 or k == 'q':
                cap.release()
                cv2.destroyAllWindows()
                sys.exit(0)
        
            
thread1 = Reader()
thread1.newData.connect(update)
thread1.start()

########################             

I guess it is quite easy to solve and I probably miss something obvious.

Siemovit

Reply all
Reply to author
Forward
0 new messages