Python 去除图片的多种颜色,黑色除外(黑色为单一颜色,可以参考去除单一颜色进行识别,统计占比等等),代码如下:
import cv2
image = cv2.imread("D:\\CSDN\\Python\\mofang.jpeg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,45, 255, cv2.THRESH_BINARY_INV)[1]
thresh = 255 - thresh
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
result = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.imwrite('result.png', result)
cv2.waitKey()
效果如下:
去除单一颜色(蓝色)的代码如下:
import cv2
img = cv2.imread("D:\\CSDN\\Python\\mofang.jpeg")
print(img.shape)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if(img[i,j,0]/(float(sum(img[i,j,:])))>0.36):
img[i,j,:] = 255
cv2.imshow("changed color picture",img)
cv2.imwrite('result2.png', img)
cv2.waitKey(0)
效果如下: