Home > Enterprise >  Python OpenCV, check if thresholded image is mostly white or black
Python OpenCV, check if thresholded image is mostly white or black

Time:10-28

I have a few images, I converted them to grayscale and thresholded them by the usual steps:

image = cv2.imread('img_path')
image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, frame_thresh = cv2.threshold(image_gray,128,255,cv2.THRESH_BINARY)

How can I check if the resulting image is mostly black or white? I tried using an histogram:

hist = cv2.calcHist([frame_thresh], [0], None, [2], [0, 1])
hist_ok /= hist_ok.sum()

but I tested it on two images, one of kind (one is mostly black, the other mostly white) and the resulting hist is always the same

print(hist)
>> [[1.]
   [0.]]

CodePudding user response:

You're looking for the average pixel value of the image, to do that you can use numpy:

import numpy as np
avg_color_per_row = np.average(frame_thresh, axis=0)
avg_color = np.average(avg_color_per_row, axis=0)

it outputs a value that ranges from 0 to 255.

CodePudding user response:

After thresholding your image contains only black (0) and white (255) pixels. You can use countNonZero function to calculate the number of non-zero pixels (not black) and compare it with image size.

Alternatively you can just calculate mean value of an image. If its lower than 127 (half of the range) image is mostly black.

  • Related