2017-04-12 50 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)