如何裁剪轮廓的中间部分?

时间:2019-05-28 06:42:28

标签: python pycharm contour

我是图像处理的新手,也是python的新手。您能正确解释如何获得结果吗?这是我的代码:

import cv2
import numpy as np
img = cv2.imread("C:\\Users\\shashisanha\\Desktop\\shapes.jpg", cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
contours,_=cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    approx = cv2.approxPolyDP(cnt , 0.01*cv2.arcLength(cnt, True), True)
    cv2.drawContours(img,[approx],0,(0) , 5)
    if len(approx)==3:
        print(3)
cv2.imshow("shape",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

这仅用于查找轮廓,现在我想将其裁剪。

1 个答案:

答案 0 :(得分:0)

首先,找到轮廓的边界框的尺寸:
x,y,w,h = cv2.boundingRect(cnt)
然后创建一个新图像,其中包含boundingrect的区域:
subimg = img[y:y+h,x:x+w]