我对 OpenCV 还很陌生,我必须为大学做一些工作。我的问题是使背景完全白色(背景已经是白色的但有一些污渍)。为此我使用了这段代码:
这是我使用的原始图像:
我得到的结果只是用黑色绘制的对象的边界框,这是结果图像:
这是我使用的代码:
import cv2
import numpy as np
image = cv2.imread('./MCP_tmp_picam_final.jpg')
original = image.copy()
gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,225,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,21,2)
# Draw boundingboxes onto a mask
mask = np.zeros(original.shape[:2], dtype=np.uint8)
cnts,_ = cv2.findContours(thresh, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(cnts):
area = cv2.contourArea(c)
# Ignore contours that are too small or too large
if area < 1000 or 100000 < area: #100000
continue
rect = cv2.minAreaRect(c)
#print(rect)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(mask, [box], 0, (255,255,255), 2)
cv2.drawContours(image,[box],0,(0,0,255),2)
# Bitwise-and for result
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)
cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.waitKey()
结果应该具有完全白色背景的孔组件。如果有人能帮助我那就太好了。
PS:我在匹配算法中使用结果图像,但这应该是下一步。
我可能误解了这个问题,但我认为这样的东西可能就是你想要的:
import numpy as np
image = cv2.imread('./MCP_tmp_picam_final.jpg')
mask = np.any(image > 100, axis=2)
image[mask] = 255
cv2.imshow('result', image)
cv2.waitKey()