我想从下图裁剪手机:
为此,我尝试检测图像中的矩形,然后使用以下代码裁剪图像:
import cv2
import numpy as np
img = cv2.imread('rt1.jpg')
imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret , thrash = cv2.threshold(imgGry, 240 , 255, cv2.CHAIN_APPROX_NONE)
contours , hierarchy = cv2.findContours(thrash, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
j=0
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True)
cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
if len(approx) == 4 :
x, y , w, h = cv2.boundingRect(approx)
cv2.putText(img, "mobile", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
out = img[y:y+h,x:x+w]
cv2.imwrite('cropped'+str(j)+'.jpg', out)
j = j+1
cv2.imshow('shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
但这并没有影响手机。您能否建议对代码进行任何改进以获得所需的结果
不需要对轮廓进行近似。对于该特定图像,您将获得一个大轮廓,您可以简单地从中获取边界矩形,并裁剪所需的部分。我可选地添加了背景透明设置
这将是具有透明度的输出图像:
在原始代码中,在
cv2.threshold
调用中有cv2.CHAIN_APPROX_NONE
。碰巧,该值等于1
,也就是cv2.THRESH_BINARY_INV
。然而,你应该注意这些细节此外,我在这里使用
cv2.RETR_EXTERNAL
而不是cv2.RETR_TREE
,因为您只有一个对象,因此找到最外部的轮廓就足够了相关问题 更多 >
编程相关推荐