2013-12-23 134 views
0

我試圖找到附加圖像的t恤的輪廓。 FindContours會在T恤周圍返回一個矩形框,並且不會找到任何其他輪廓。 我的目標是找到t恤的外部輪廓。 任何想法我做錯了什麼?python opencv發現輪廓錯誤

下面的代碼。 謝謝。 李

from PIL import Image 
import os 
import numpy 
import bs4 
import scipy 
import cv2 

STANDARD_SIZE = (200, 200) 

# read image file 
image_obj_orig = cv2.imread(image_file) 
image_name = os.path.split(image_file)[-1] 
name, extension = os.path.splitext(image_name) 

# normalize to a standard size 
image_obj = cv2.resize(image_obj_orig, STANDARD_SIZE) 

# convert to grey-scale 
greyscale_image = cv2.cvtColor(image_obj,cv2.COLOR_BGR2GRAY) 
cv2.imwrite(os.path.join(trg_dir, name + '_GS' + extension), greyscale_image) 

h, w = greyscale_image.shape[:2] 
contours, hierarchy = cv2.findContours(greyscale_image.copy(), cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) 

cv2.drawContours(greyscale_image, contours, -1, (128,255,255)) 
cv2.imshow('image', greyscale_image) 
+1

有一些二值化(閾值,精明的,等等)的灰度和findContours – berak

+0

高斯模糊之間需要 - >門檻 - >找到輪廓。 – M4rtini

回答

1

這適用於這個特定的圖像,它可能不適合其它圖像工作。例如,模糊可能需要調整。來自OpenCV的文檔查找任何一個功能參數:

import cv2 
import matplotlib.pyplot as plt 
image = cv2.imread('t1NHA.jpg') 
#padding since the t-shirt is touching the border, without this we cant get a continious contour around it. 
image = cv2.copyMakeBorder(image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[255, 255, 255]) 
imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
imgray = cv2.GaussianBlur(imgray, (9, 9), 0) 
ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) 
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 
cv2.drawContours(image, contours, -1, (0, 255, 0), 3) 
plt.imshow(image) 
plt.show() 
1

你有沒有嘗試過這樣的:

ret,thresh = cv2.threshold(greyscale_image.copy(),127,255,cv2.THRESH_BINARY_INV) # add this line before findContours 
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)