gpt4 book ai didi

opencv - OpenCV查找此图像的轮廓以进行裁剪和旋转

转载 作者:行者123 更新时间:2023-12-02 17:20:06 26 4
gpt4 key购买 nike

我正在尝试检测此图像的轮廓,以便在openCV中对其进行裁剪。
我想出了有效的代码,但是,如果图像上有一些轻微的背景,它将失败。
图像处理:
enter image description here
检测边界(蓝点):
enter image description here
裁剪/轮播:
enter image description here
但是,对于像这样的图像和一些背景光,它将不起作用:
enter image description here
预处理:
enter image description here
边界检测:
enter image description here

def preProcessing(img):
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

adaptive_thresold1 = 31
adaptive_thresold2 = 7

blur = cv2.blur(imgGray, (3, 3))
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,adaptive_thresold1,adaptive_thresold2)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)

stackedImages = hp.stackImages(0.1,([img,thresh, close],[img,thresh, close]))
cv2.imshow("WorkFlow", stackedImages)
cv2.waitKey(0)
return thresh


def getContours(img):
biggest = np.array([])
maxArea = 0
img = cv2.bitwise_not(img)
contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

for cnt in contours:
area = cv2.contourArea(cnt)
if area>5000:
print (area)

#cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)

if area >maxArea and len(approx) == 4:
biggest = approx
maxArea = area
print ("ok")

print (biggest)
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.drawContours(out, biggest, -1, (255, 0, 0), 50)

stackedImages = hp.stackImages(0.1,([img,out],[img,out]))
cv2.imshow("WorkFlow", stackedImages)
cv2.waitKey(0)

return biggest
有什么建议可以使此代码更可靠吗?

最佳答案

代替使用自适应阈值,尝试使用Otsu's thresholding
更改此行

thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,adaptive_thresold1,adaptive_thresold2)
在您的代码中-
retval_blue, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
图片中这对我有用。

关于opencv - OpenCV查找此图像的轮廓以进行裁剪和旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62658671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com