B
B
bezvozni2020-05-24 17:06:01
Python
bezvozni, 2020-05-24 17:06:01

How to count the number of non-black pixels in an image?

I'm currently working on the code:

import cv2
import video

if __name__ == '__main__':
    cv2.namedWindow( "original" )
    #cv2.namedWindow( "original2" )
    cv2.namedWindow( "original3" )
    
    cap = cv2.VideoCapture("z:/input.mp4")
    #https://stackoverflow.com/questions/33650974
    cap2 = cv2.VideoCapture("z:/input.mp4")
    #https://stackoverflow.com/questions/10475198
    frame_number = cap2.get(cv2.CAP_PROP_POS_FRAMES)
    cap2.set(cv2.CAP_PROP_POS_FRAMES, frame_number+1)
    
    while True:
        flag, img = cap.read()
        flag2, img2 = cap2.read()
        #https://stackoverflow.com/questions/2142599
        img3 = cv2.absdiff(img, img2)
        #https://stackoverflow.com/questions/21425992
        #https://stackoverflow.com/questions/45817037
        #img3 = cv2.subtract(img, img2)
        count = cv2.countNonZero(img3)
        print(count)
        
        try:
            cv2.imshow('original', img)
            #cv2.imshow('original2', img2)
            cv2.imshow('original3', img3)
        except:
            cap.release()
            cap2.release()
            raise
                
        ch = cv2.waitKey(5)
        if ch == 27:
            break
            
    cap.release()
    cap2.release()
    cv2.destroyAllWindows()


I see that there is an option with
count = cv2.countNonZero(img3)
but I get an error
error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\core\src\count_non_zero.dispatch.cpp:124: error: (-215:Assertion failed) cn == 1 in function 'cv ::countNonZero'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bezvozni, 2020-05-24
@bezvozni

//берём все не нули
nozero = img3[img3 > 0]
//считаем кол-во и выводим
print(len(nozero))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question