How do I count the number of nonzero pixel using frames in live camera? It works with image but it doesn't in frames. I'm using opencv

291 Views Asked by At
import cv2
import pickle
import cvzone
import numpy as np

#video feed
cap = cv2.VideoCapture(0)


with open("CarParkPos", "rb") as f:
    posList = pickle.load(f)

width, height = 100, 50

def checkParkingSpace(frameProcess):
    for pos in posList:
        x,y = pos

        frameCrop = frame[y:y+height, x:x+width]
        cv2.imshow(str(x*y), frameCrop)
        count = cv2.countNonZero(frameCrop)
        cvzone.putTextRect(frame, "asd", (x,y+height-3), scale = 1, thickness=2, offset=0)

cv2.countNonZero doesn't seem to work when counting pixels in a live camera, but it works fine when using a video file.

#converted rgb camera to black and white
while True:
    ret, frame = cap.read()
    frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frameBlur = cv2.GaussianBlur(frameGray, (3,3), 1)
    frameThreshold = cv2.adaptiveThreshold(frameBlur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                           cv2.THRESH_BINARY_INV, 25, 16)
    frameMedian = cv2.medianBlur(frameThreshold,5)
    kernel = np.ones((1,1), np.uint8)
    frameDilate = cv2.dilate(frameMedian,kernel, iterations = 1)

    checkParkingSpace(frameDilate)
    
    #writing the rectangle shapes in camera
    for pos in posList:
        cv2.rectangle(frame, pos, (pos[0] + width, pos[1] + height), (0, 200, 0), 2)

    cv2.imshow("Frame", frame)
    cv2.waitKey(1)

I don't fully understand all the codes since I just watched a tutorial. What I'm trying to do is exactly the one in the video https://www.youtube.com/watch?v=caKnQlCMIYI , but instead of using video file I want to use a live camera.

1

There are 1 best solutions below

0
On
for pos in posList:
    x,y = pos

    frameCrop = frame[y:y+height, x:x+width]
    cv2.imshow(str(x*y), frameCrop)
    count = cv2.countNonZero(cv2.Canny(frameCrop, 100, 200))
    cvzone.putTextRect(frame, str(count), (x,y+height-3), scale = 1, thickness=2, offset=0)

What I did was canny the frame then count the non-black pixel.