如何使用Python裁剪图像中的矩形形状

4

有人能给我关于如何裁剪这两个矩形框并保存它们的建议吗?

sample image

我已经尝试过这段代码,但无法很好地进行裁剪。
import cv2;
import numpy as np;

# Run the code with the image name, keep pressing space bar

# Change the kernel, iterations, Contour Area, position accordingly
# These values work for your present image

img = cv2.imread("your_image.jpg", 0);
h, w = img.shape[:2]
kernel = np.ones((15,15),np.uint8)

e = cv2.erode(img,kernel,iterations = 2)  
d = cv2.dilate(e,kernel,iterations = 1)
ret, th = cv2.threshold(d, 150, 255, cv2.THRESH_BINARY_INV)

mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(th, mask, (200,200), 255); # position = (200,200)
out = cv2.bitwise_not(th)
out= cv2.dilate(out,kernel,iterations = 3)
cnt, h = cv2.findContours(out,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(cnt)):
            area = cv2.contourArea(cnt[i])
            if(area>10000 and area<100000):
                  mask = np.zeros_like(img)
                  cv2.drawContours(mask, cnt, i, 255, -1)
                  x,y,w,h = cv2.boundingRect(cnt[i])
                  crop= img[ y:h+y,x:w+x]
                  cv2.imshow("snip",crop )
                  if(cv2.waitKey(0))==27:break

cv2.destroyAllWindows()

这是结果。它只裁剪了较小的方框。我想要的是裁剪两个正方形。

sampled crop


1
你的 'area<100000' 对于大矩形来说太小了,你的图像是960x720,仅覆盖了50%,至少需要345000...我建议放置更大的图像或将其删除。 - api55
谢谢你的提示,它确实起作用了。我使用试错法改变大小。但是我又遇到了一个问题,它不能完美地裁剪,就像我想要的那样。你能帮我解决这个问题吗?我附上了示例裁剪图,它并不完美。我正在使用这个转换方法和扭曲,但我只是一个初学者,所以很难。谢谢你,我会感激不尽。 - Crispolo Bernardino
1个回答

1
如果您有矩形的坐标,可以尝试以下操作:
cropped = img [y1:y2, x1:x2]

cv2.imwrite('cropped.png', cropped)

第一行根据给定的坐标裁剪图像,假设(y1

谢谢您的回复,但是坐标随着图片的更改而更改,因为我正在按照模式进行裁剪,而该模式是图像中的正方形框。不幸的是,我不能使用坐标裁剪,因为当我将代码用于不同的图像时,框的坐标会更改,因为不同的图像没有固定的坐标。 - Crispolo Bernardino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接