2017-01-26 1903 views
4

我想使用cv2.approxPolyDP()來提取圖像中的輪廓近似值。下面是我使用的圖像:OpenCV - 正確使用cv2.approxPolyDP()

map of UK

我的代碼試圖隔離主島和定義並畫出輪廓逼近和輪廓船體。我已經繪製在綠色中發現的輪廓,近似紅色:

import numpy as np 
import cv2 

# load image and shrink - it's massive 
img = cv2.imread('../data/UK.png') 
img = cv2.resize(img, None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC) 

# get a blank canvas for drawing contour on and convert img to grayscale 
canvas = np.zeros(img.shape, np.uint8) 
img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 

# filter out small lines between counties 
kernel = np.ones((5,5),np.float32)/25 
img2gray = cv2.filter2D(img2gray,-1,kernel) 

# threshold the image and extract contours 
ret,thresh = cv2.threshold(img2gray,250,255,cv2.THRESH_BINARY_INV) 
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) 


# find the main island (biggest area) 
cnt = contours[0] 
max_area = cv2.contourArea(cnt) 

for cont in contours: 
    if cv2.contourArea(cont) > max_area: 
     cnt = cont 
     max_area = cv2.contourArea(cont) 

# define main island contour approx. and hull 
perimeter = cv2.arcLength(cnt,True) 
epsilon = 0.01*cv2.arcLength(cnt,True) 
approx = cv2.approxPolyDP(cnt,epsilon,True) 

hull = cv2.convexHull(cnt) 

# cv2.isContourConvex(cnt) 

cv2.drawContours(canvas, cnt, -1, (0, 255, 0), 3) 
cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3) 
## cv2.drawContours(canvas, hull, -1, (0, 0, 255), 3) # only displays a few points as well. 

cv2.imshow("Contour", canvas) 
k = cv2.waitKey(0) 

if k == 27:   # wait for ESC key to exit 
    cv2.destroyAllWindows() 

這裏是所產生的圖像:

enter image description here

第一個圖像繪製輪廓爲綠色。第二種將近似值繪製爲紅色 - 如何將此近似值繪製爲連續閉合曲線?

documentation並不十分清楚,既不是tutorial,但我的理解是,cv2.approxPolyDP()應該定義一個連續,封閉的曲線,這是我應該能夠cv2.drawContours()繪製。那是對的嗎?如果是這樣,我做錯了什麼?

+0

什麼是你的問題?你想實現什麼?您的代碼不符合可視化。 'cv2.approxPolyDP()'返回點的列表,是的,你可以將它們繪製成曲線,但我不確定它是如何處理自交的(它存在於你的初始曲線上)。 – avtomaton

+0

@avtomaton - 我已經更新了我的問題 - 如果不使用'drawContours',我如何將返回的點列表繪製爲連續曲線? – Aidenhjj

+0

我仍然不確定你正在繪製什麼。你是正確的,你應該使用'drawContours'來繪製輪廓,但是在你的代碼中,你將它們繪製在同一個畫布上,並且它們顯示一張圖片,但是你附加的圖片是不同的!你能否發佈相關的代碼?我仍然認爲這可能是由於自交。嘗試繪製線是爲了找出它。 – avtomaton

回答

11

問題是隻在可視化中:drawContours期望輪廓的數組(列表如果是python),而不僅僅是一個numpy數組(從approxPolyDP返回)。

解決方案如下:更換

cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3) 

cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 3) 
相關問題