本文介绍了使用OpenCV检查图像是否全部为白色像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OpenCV(Python)编写脚本,以将图像分成不同的部分,以便稍后在其上的每个部分上运行OCR.我已经获得了将源图像分割成我需要的所有框的脚本,但是它也附带了许多普通的白色图像.

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.

我很好奇,是否可以使用OpenCV检查图像是否仅为白色像素.我是这个图书馆的新手,所以有关此的任何信息都将有所帮助.

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.

谢谢!

推荐答案

方法#1: np.mean

计算图像的平均值.如果等于255,则图像由所有白色像素组成.

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')

方法2:: cv2.countNonZero

您可以使用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:

输入图像#1(由于背景为白色,因此不可见):

Input image #1 (invisible since background is white):

输入图片#2

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()

这篇关于使用OpenCV检查图像是否全部为白色像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:02