如果存在白色和黑色背景，如何将整个图像的背景转换为白色？

问题描述投票：1回答：2

python-3.x opencv
2个回答
1

• 转换为HSV
• 找到每行的平均饱和度，并选择平均饱和度超过阈值的行
• 灰度化那些行，反转并阈值它们

``````#!/usr/bin/env python3

import cv2
import numpy as np

# Make HSV and extract S, i.e. Saturation
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
s=hsv[:,:,1]
# Save saturation just for debug
cv2.imwrite('saturation.png',s)

# Make greyscale version and inverted, thresholded greyscale version
gr = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
_,grinv = cv2.threshold(gr,127,255,cv2.THRESH_BINARY_INV)

# Find row numbers of rows with colour in them
meanSatByRow=np.mean(s,axis=1)
rows = np.where(meanSatByRow>50)

# Replace selected rows with those from the inverted, thresholded image
gr[rows]=grinv[rows]

# Save result
cv2.imwrite('result.png',gr)
``````

0

``````#!/usr/bin/env python3

import cv2
import numpy as np

# Load image, greyscale and threshold

# Threshold and invert
_,thr = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
inv   = 255 - thr

# Perform morphological closing with square 7x7 structuring element to remove details and thin lines
SE = np.ones((7,7),np.uint8)
closed = cv2.morphologyEx(thr, cv2.MORPH_CLOSE, SE)
# DEBUG save closed image
cv2.imwrite('closed.png', closed)

# Find row numbers of dark rows
meanByRow=np.mean(closed,axis=1)
rows = np.where(meanByRow<50)

# Replace selected rows with those from the inverted image
im[rows]=inv[rows]

# Save result
cv2.imwrite('result.png',im)
``````