Home > Enterprise >  Error in cv2.cvtColor converting an image to HSV (using cv2.COLOR_BGR2HSV)
Error in cv2.cvtColor converting an image to HSV (using cv2.COLOR_BGR2HSV)

Time:05-25

When I open multiple images from a folder and try to convert each into BGR2HSV, I receive this error:

Traceback (most recent call last): File "create_gestures_manual.py", line 123, in get_img(lab_path) File "create_gestures_manual.py", line 114, in get_img store_images(g_id, dirr) File "create_gestures_manual.py", line 61, in store_images imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) cv2.error: OpenCV(4.5.2) /tmp/pip-req-build-wu1ri_rx/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::{anonymous}::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::impl::{anonymous}::Set<3, 4>; VDcn = cv::impl::{anonymous}::Set<3>; VDepth = cv::impl::{anonymous}::Set<0, 5>; cv::impl::{anonymous}::SizePolicy sizePolicy = cv::impl::::NONE; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]'

Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1

Below are snippet of my code:

while True:
    framee = cv2.imread(dirr,0)
    img = cv2.flip(framee, 1)
    cv2.imshow('IMG',img)
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

What does this mean?. Please help me out. And how to solve this

CodePudding user response:

you read your image as grayscale image. change this part:

framee = cv2.imread(dirr)

to have bgr image and then convert bgr to hsv.

CodePudding user response:

The source of the error is that framee is a single channel grayscale image (and so is img which is created based on it). It is not a 3 channel color image, and therefore cannot be converted directly to hsv.

As you can see in this link: imread, the 2nd parameter flags determines the format of the read image.

In your code you use 0, which internally maps to IMREAD_GRAYSCALE. So even if your image file contains an rgb image, it will be converted to 1 channel grayscale.

Since the default for flags is IMREAD_COLOR, you can simply use:

framee = cv2.imread(dirr)

On a side note: even if you don't want this default, it's recommended to use the opencv enum values (e.g. cv2.IMREAD_GRAYSCALE) instead of an integer. Doing so you would never encounter this problem.

  • Related