如何找到轮廓的坐标并裁剪它?

时间:2017-04-12 11:42:34

标签: python-3.x opencv image-processing

我试图找出具有最大面积的轮廓,获取矩形区域的坐标并裁剪出区域并显示。 ocean.jpg

这是代码:

    import cv2
    import numpy as np

    img = cv2.imread('ocean.jpg')

    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret,thresh=cv2.threshold(gray,127,255,0)
    x,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]

    cv2.drawContours(img,contours,-1,(0,255,0),1)
    cv2.imshow('Contours',img)
    a=[]
    for i in range (len(contours)):   
        a.append(cv2.contourArea(contours[i]))
    z=(max(a))
    print (contours[a.index(z)])

1 个答案:

答案 0 :(得分:0)

largestContourArea = 0
largestContour = 0
for cnt in contours:
    contourArea = cv2.contourArea(cnt)
    if( contourArea > largestContourArea):
        largestContour = cnt
        largestContourArea = contourArea

# This finds the bounding rectangle
# x,y are the co-ordinates of left-top point and w,h are width and height respectively
x,y,w,h = cv2.boundingRect(largestContour)

# This is simple slicing to get the "Region of Interest"
ROI = img[y:y+h,x:x+w]
cv2.namedWindow("Largest Contour",cv2.WINDOW_NORMAL)
cv2.imshow("Largest Contour",ROI)
cv2.waitKey(0)