I have some image arrays with a shape of (128,256,2) which have two color channels. I am trying to open the image array using the openCV's imshow but I am continuously getting the following error: >
Invalid number of channels in input image:
> 'VScn::contains(scn)'
> where
> 'scn' is 2
I understand openCV can't open image array with two color space. Is there any way to open the image with the two color channels or to compute element-wise average and convert it an array with one color channel? Kindly help please!
> cv2.imshow("Window", img)
CodePudding user response:
Here is one way that demonstrates adding a black channel to two channels of an image in Python/OpenCV.
Input:
import cv2
import numpy as np
# read a 3 channel image
img = cv2.imread('lena.png')
h, w = img.shape[:2]
# separate channels
b,g,r = cv2.split(img)
# create black image the same size as image
black = np.zeros((h,w), dtype=np.uint8)
# replace the red channel with black
result = cv2.merge([b,g,black])
# save results
cv2.imwrite('lena_black.png', result)
# show results
cv2.imshow('result', result)
cv2.waitKey(0)
Result:
If you already have a 2 channel image, then simply create the black image and use np.dstack([2-channel-image, black])
to make a 3 channel image.
CodePudding user response:
OpenCV does not recognise images with only 2 channels, the solution is to add a black channel.
OpenCV images are represented as numpy
arrays:
import cv2
img = cv2.imread(PATH_TO_IMG)
# This returns <class 'numpy.ndarray'>.
type(img)
Now we can use numpy
functions to add the 3rd channel (black):
import cv2
import numpy as np
H, W, _ = img.shape
img = np.append(img, np.zeros((H, W, 1)), axis=-1)
cv2.imshow(window_name, img)
cv2.waitKey()
Credits to @fmw42.
Or, you could take the element-wise average across channels, and display it as a grayscale image:
import cv2
import numpy as np
img = np.average(img, axis=-1)
cv2.imshow(window_name, img)
cv2.waitKey()