2017-04-12 159 views
0

我试图找出具有最大面积的轮廓,获得矩形区域的坐标并裁剪出该区域并显示。 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

替换'cv2.CHAIN_APPROX_SIMPLE'到'cv2.CHAIN_APPROX_NONE'。然后,对象“轮廓”将具有所有点的坐标。 –

回答

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)