前言
本篇博客使用Python+OpenCV判断图像是黑底还是白底,利用图像对角线上的黑白像素点个数进行判断,详情见下文。
本篇博客内容包含代码逻辑、说明、依赖、实现,这几部分。代码实现部分包含2种实现方式,1种进行二值化操作,1种不进行二值化操作。Python版本为3.6。
代码逻辑
- 导入OpenCV第三方库。
- 读入图像。
- 图像灰度化。
- 图像二值化。
- 获取图像2条对角线上黑白像素点个数。
- 比较黑白像素点个数,若黑像素多于白像素,则为黑底;否则为白底。
代码说明
- 代码包含2种实现方式,1种进行二值化操作,即
BorW_binary()
函数;1种不进行二值化操作,即BorW_not_binary()
函数。 main
函数中可以通过imread()
更改输入图像、也可通过bwThresh
变量更改判断黑白像素的阈值。
代码依赖
Python == 3.6
opencv-python == 4.5.5.62
代码实现
# This script is used to judge a image is black based or white based
import cv2
# binarization
def BorW_binary(img, bwThresh):
gray = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) # gray image
ret, thresh = cv2.threshold(gray, bwThresh, 255, cv2.THRESH_BINARY) # binarization
# get h and w of img
imgShape = img.shape
h = imgShape[0]
w = imgShape[1]
# init black and white point number
blackNum, whiteNum = 0, 0
k = h / w
for x in range(w):
y1 = int(k * x)
y2 = int((-k) * x + h - 1)
# prevent overflow
if 0 <= y1 <= (h - 1) and 0 <= y2 <= (h - 1):
# first diagonal line
if thresh[y1][x] == 0:
blackNum += 1
else:
whiteNum += 1
# second diagonal line
if thresh[y2][x] == 0:
blackNum += 1
else:
whiteNum += 1
print(blackNum, whiteNum)
if blackNum > whiteNum:
print("black based image")
else:
print("white based image")
# not binary
def BorW_not_binary(img, bwThresh):
gray = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) # gray image
# ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # binarization
# get h and w of img
imgShape = img.shape
h = imgShape[0]
w = imgShape[1]
# init black and white point number
blackNum, whiteNum = 0, 0
k = h / w
for x in range(w):
y1 = int(k * x)
y2 = int((-k) * x + h - 1)
# prevent overflow
if 0 <= y1 <= (h - 1) and 0 <= y2 <= (h - 1):
# first diagonal line
if gray[y1][x] <= bwThresh:
blackNum += 1
else:
whiteNum += 1
# second diagonal line
if gray[y2][x] <= bwThresh:
blackNum += 1
else:
whiteNum += 1
print(blackNum, whiteNum)
if blackNum > whiteNum:
print("black based image")
else:
print("white based image")
if __name__ == "__main__":
img = cv2.imread("../img/handbag.png")
bwThresh = 127 # threshold value of black or white
BorW_binary(img, bwThresh)
BorW_not_binary(img, bwThresh)