简体   繁体   English

python opencv错误找到轮廓

[英]python opencv error finding contours

I'm trying to find the contour of the attached image of a tshirt. 我正在尝试查找T恤所附图像的轮廓。 FindContours returns a rectangular frame around the tshirt, and doesn't find any additional contours. FindContours返回T恤周围的矩形框,并且找不到其他轮廓。 My goal is to find the external contour of the tshirt. 我的目标是找到T恤的外部轮廓。 Any idea what am I doing wrong? 知道我在做什么错吗?

Code below. 下面的代码。 Thanks. 谢谢。 Li

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)

This works for this specific image, it may not work for other images. 这适用于该特定图像,可能不适用于其他图像。 The blur might need adjusting for example. 例如,模糊可能需要调整。 Look up any of the function parameters from the opencv documentation: 从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()

Have you tried this: 您是否尝试过:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM