我想找出黑色背景中白色区域(对于图片1)的坐标,以便对其进行裁剪。我想分别修剪所有这些白色区域。因此,我正在接近这些形状的轮廓,但是它不起作用。同时,我将它作为一个对象来处理,但事实并非如此。因此,我必须如何接近这些白色区域才能进行检测和裁剪?
import numpy as np
img = cv2.imread("image.png")
bw = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(bw,127,255,0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cntx1 = contours[0][0]
cntx = contours[0][1]
pt1 = (cntx1[0][0],cntx1[0][1])
pt2 = (cntx[0][0],cntx[0][1])
cv2.circle(img,pt1,5,(0,255,0),-1)
cv2.circle(img,pt2, 5, (0,255,0),-1)
cv2.imshow('f',img)
cv2.waitKey(0)
cv2.destroyAllWindows() ```
您可以先按cv2.bitwise_not
,然后按cv2.add
。因为我没有您的原始图片,所以我制作了一张。
img = cv2.imread("flower.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,180,255,cv2.THRESH_BINARY)
bit_not = cv2.bitwise_not(thresh)
bit_not_bgr = cv2.cvtColor(bit_not, cv2.COLOR_GRAY2BGR)
res = cv2.add(bit_not_bgr,img)
cv2.imshow("img",img)
cv2.imshow("thresh",thresh)
cv2.imshow("bit_not",bit_not_bgr)
cv2.imshow("res",res)