Tag Archives: python opencv Error

[Solved] python opencv Error: findContours() Can only use the Grayscale

Original program

import cv2
import numpy as np


def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# Read the image
img = cv2.imread('contours.png')
cv_show('contours', img)

# Grayscale and binarization
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]
cv_show('thresh', thresh)

# Find the outline
cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]

# Draw the outline
draw = img.copy()
res = cv2.drawContours(draw, cnt, -1, (0, 0, 255), 2)
cv_show('res', res)

report errors

Traceback (most recent call last):
  File "C:/Users/ccccj/PycharmProjects/a_opencv/opencv/opencv_notebook/ppt/ppt_season_2-8/2-7_notebook/image_operation/contours.py", line 21, in <module>
    cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
cv2.error: OpenCV(3.4.11) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-7_3trius\opencv\modules\imgproc\src\contours.cpp:197: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFindContours_Impl'

Reason: the SRC of findcontours() function must be a grayscale image. The original program uses img, which is changed to the following:

# Find the outline
# cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]


# Modify to:
cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]