[英]How to remove the background of an image
一种可能的解决方案是通过将图像转换为 CMYK 颜色空间并提取 K(Key - black)通道并将其阈值化以实现二值图像来提取暗像素。
手动计算 K 通道并使用固定值(在本例中为 150)设置阈值。 代码如下所示; 结果
import cv2
import numpy as np
# get grayscale image
def get_grayscale(image):
# Convert to float and divide by 255:
imgFloat = image.astype(np.float64) / 255.
# Calculate channel K:
kChannel = 1 - np.max(imgFloat, axis=2)
# Convert back to uint 8:
kChannel = (255 * kChannel).astype(np.uint8)
# Threshold image:
binaryThresh = 150
_, binaryImage = cv2.threshold(kChannel, binaryThresh, 255, cv2.THRESH_BINARY)
return cv2.bitwise_not(binaryImage)
if __name__ == '__main__':
image = cv2.imread("input.png")
gray = get_grayscale(image)
cv2.imshow("image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.