问题
I am working on a script with OpenCV (Python) to split up an image into different sections in order to run OCR on each section on it later. I've got the script splitting up the source image into all the boxes I need, but it also comes along with a number of plain white images as well.
I'm curious if there's a way to check if an image is only white pixels or not with OpenCV. I'm very new to this library, so any information on this would be helpful.
Thanks!
回答1:
Method #1: np.mean
Calculate the mean of the image. If it is equal to 255
then the image consists of all white pixels.
if np.mean(image) == 255:
print('All white')
else:
print('Not all white')
Method #2: cv2.countNonZero
You can use cv2.countNonZero
to count non-zero (white) array elements. The idea is to obtain a binary image then check if the number of white pixels is equal to the area of the image. If it matches then the entire image consists of all white pixels. Here's a minimum example:
Input image #1 (invisible since background is white):
All white
Input image #2
Not all white
import cv2
import numpy as np
def all_white_pixels(image):
'''Returns True if all white pixels or False if not all white'''
H, W = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
pixels = cv2.countNonZero(thresh)
return True if pixels == (H * W) else False
if __name__ == '__main__':
image = cv2.imread('1.png')
if all_white_pixels(image):
print('All white')
else:
print('Not all white')
cv2.imshow('image', image)
cv2.waitKey()
来源:https://stackoverflow.com/questions/59758904/check-if-image-is-all-white-pixels-with-opencv