简体   繁体   English

在Python中使用OpenCV findContours

[英]OpenCV findContours in python

I am working in python on openCV 3.0. 我在openCV 3.0上的python中工作。 In order to find the largest white pixel region, first of all thresholded gray image to binary image. 为了找到最大的白色像素区域,首先将阈值灰度图像转换为二值图像。

import cv2

import numpy as np

img = cv2.imread('graimage.png') 

img = cv2.resize(img,(400,500))

gray = img.copy()

(thresh, im_bw) = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY )

derp,contours,hierarchy = cv2.findContours(im_bw,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

cnts = max(cnts, key=cv2.contourArea)

But it shows error as follows. 但它显示如下错误。

cv2.error: ..../opencv/modules/imgproc/src/contours.cpp:198: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours. cv2.error:.... / opencv / modules / imgproc / src / contours.cpp:198:错误:( - 210)[开始]当模式时,FindContours仅支持CV_8UC1图像!= CV_RETR_FLOODFILL否则仅在函数cvStartFindContours中支持CV_32SC1图像。

It looks like this was answered in the comments, but just to mark the question as answered: 看起来在评论中回答了这个问题,但只是将问题标记为已回答:

CV_8UC1 means 8-bit pixels, unsigned, and only one channel, so grayscale. CV_8UC1表示8位像素,无符号,只有一个通道,因此为灰度。 It looks like you're reading it in with 3 color channels, or CV_8UC3. 看起来你正在用3色通道或CV_8UC3读它。 You can check the image type by printing img.dtype and img.shape . 您可以通过打印img.dtypeimg.shape来检查图像类型。 The dtype should be uint8, and the shape should be (#, #), indicating two dimensions. dtype应为uint8,形状应为(#,#),表示两个维度。 I'm guessing you'll see that shape prints (#, #, 3) for your image as-is, indicating three color channels. 我猜你会看到你的图像的形状打印(#,#,3),表示三个颜色通道。

As @user3515225 said, you can fix that by reading the image in as grayscale using cv2.imread('img.png', cv2.IMREAD_GRAYSCALE) . 正如@ user3515225所说,你可以通过使用cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)以灰度读取图像来解决这个问题。 That assumes you have no use for color anywhere else, though. 但是,假设您在其他任何地方都没有使用颜色。 If you want a separate grayscale copy of the image, then replace gray = img.copy() with gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) instead. 如果你想要一个单独的图像灰度副本 ,那么用gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)替换gray = img.copy()

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

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