analitics

Pages

Friday, March 3, 2023

Python 3.11.0 : OpenCV - part 001.

A few years ago I made a series of several tutorials about python and OpenCV. They were functional, but I know that due to time, changes in development can lead to changes in the source code. Today I tested a script with this python package and it worked quite well.
In some cases, depending on the web camera and the operating system, the way of capturing images can be modified with the two specific elements: cv2.VideoCapture(cv2.CAP_DSHOW) or cv2.VideoCapture(cv2.CAP_V4L2)
This is the source code I used:
import cv2
import numpy as np
import time 

def draw_hist(name, gray):
    hist = cv2.calcHist([gray], [0], None, [256], [0,256])
    MAX = max(hist)
    plot = np.zeros((512,1024))
    for i in range(255):
        x1 = 4*i
        x2 = 4*(i+1)
        y1 = int(hist[i]*512/MAX)
        y2 = int(hist[i+1]*512/MAX)
        cv2.line(plot, (x1,y1), (x2,y2), 1, 3)
    cv2.imshow(name + "-gray", gray)
    cv2.imshow(name + "-hist", plot)


def main():
    cam = cv2.VideoCapture(0)
    #while cv2.waitKey(10) == -1:
    start_time = time.time()
    while time.time() - start_time < 30:
        ret, img = cam.read()
        if not ret:  # add check for empty image
            continue
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        draw_hist("cam",gray)
        cv2.waitKey(10)

if __name__=="__main__":
    main()