使用 OpenCV 检查图像是否全为白色像素

jas*_*ino 2 python opencv image pixel image-processing

我正在使用 OpenCV (Python) 编写一个脚本,将图像分成不同的部分,以便稍后在每个部分上运行 OCR。我有脚本将源图像分成我需要的所有框,但它也带有一些纯白色图像。

我很好奇是否有办法使用 OpenCV 检查图像是否只有白色像素。我对这个图书馆很陌生,所以任何关于这方面的信息都会有所帮助。

谢谢!

nat*_*ncy 12

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')
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)