Muhamed Krlić
Muhamed Krlić

Reputation: 1472

OpenCV specific color extraction

I am trying to exctract all blue channel items from an image, this is my small script:

import cv2
import argparse

parser = argparse.ArgumentParser(description='Process image signatures.')

parser.add_argument('inputfile', metavar='InFile', type=str, nargs=1,
                   help='input image file with signatures')
parser.add_argument('outputfile', metavar='OutFile', type=str, nargs=1,
                   help='output image file with signatures')

args = parser.parse_args()

img = cv2.imread(args.inputfile[0], 0)

# Convert color to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# set range for blue color
lower_range = np.array([110,50,50])
upper_range = np.array([130,255,255])

# apply mask
mask = cv2.inRange(hsv, lower_range, upper_range)

# apply color
res = cv2.bitwise_and(img,img, mask= mask)

cv2.imshow('res', res)
cv2.imwrite(args.outputfile[0], res)

Now I am getting Invalid number of channels in input image however this jpg image has at least 3 color channels. scanned paper image Full error is as follows:

$ python c:/Users/LenovoPC/Desktop/signature_extractor-master/signature_extractor-master/blue_img_extractor.py ./inputs/in1.jpg ./outputs/output1.png
Traceback (most recent call last):
  File "c:/Users/LenovoPC/Desktop/signature_extractor-master/signature_extractor-master/blue_img_extractor.py", line 16, in <module>
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.error: OpenCV(4.4.0) c:\users\appveyor\appdata\local\temp\1\pip-req-build-cff9bdsm\opencv\modules\imgproc\src\color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function '__thiscall cv::impl::`anonymous-namespace'::CvtHelper<struct cv::impl::`anonymous namespace'::Set<3,4,-1>,struct cv::impl::A0x5406ba9d::Set<3,-1,-1>,struct cv::impl::A0x5406ba9d::Set<0,5,-1>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 1

Whats exactly an issue here? Thank you.

Upvotes: 1

Views: 96

Answers (1)

Eran W
Eran W

Reputation: 1776

This is because this line before the line with the error:

img = cv2.imread(args.inputfile[0], 0)

The 0 argument is passed, which is cv::IMREAD_GRAYSCALE.

Remove the zero, or use 1 to force color:

img = cv2.imread(args.inputfile[0])

Read more in the docs: Image file reading and writing

Upvotes: 2

Related Questions