Lee Android Lee Android - 4 months ago 35
Python Question

imshow resize + count white pixels

This is a simple program to read video files from your computer. My original video is 1080p resolution. When I run the code, the program's screen (imshow) exceeds my pc's screen which is only 720p. How to resize it from 1080p to 720 or 480p. Second question, how to find the number of pixels in the screen?

My code:

import numpy as np
import cv2

cap = cv2.VideoCapture('apple.mp4')

while(cap.isOpened()):
ret, frame = cap.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()

Answer

You can use cv2.resize() to resize the image before imshow() to fit in the screen, and to get the total number of pixels in the Mat you can use gray.shape[0] * gray.shape[1]

import numpy as np
import cv2

cap = cv2.VideoCapture('apple.mp4')

while(cap.isOpened()):
    ret, frame = cap.read()
    frame = cv2.resize(frame, None, fx = 0.5, fy = 0.5, interpolation = cv2.INTER_CUBIC)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    print "No. of pixels : ", gray.shape[0] * gray.shape[1]
    # Counting the number of pixels with given value
    print "No. of white pixels : ", np.count_nonzero(gray == 255)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
Comments