Saurabh
Saurabh

Reputation: 1662

How do I convert openCV transformed images into its orignal format

I have resized my orignal image from 200x200 to 128x128 , since opencv in default read in BGR , I took care of that but after resizing it becomes grayscale(as expected) but I can't convert back to its RGB format

orignal = cv2.imread(os.path.join("/path","some_image.png"),0)

rgb = cv2.cvtColor(orignal, cv2.COLOR_BGR2RGB)

resized = cv2.resize(rgb,(128,128))

backtorgb = cv2.cvtColor(resized,cv2.COLOR_GRAY2RGB)

plt.imshow(backtorgb)

here last line gives error:

error: OpenCV(4.0.0) /io/opencv/modules/imgproc/src/color.hpp:259: error: (-2:Unspecified error) in function 'cv::CvtHelper::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::Set<1>; VDcn = cv::Set<3, 4>; VDepth = cv::Set<0, 2, 5>; cv::SizePolicy sizePolicy = (cv::SizePolicy)2u; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]' Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 3

Upvotes: 1

Views: 5169

Answers (2)

nathancy
nathancy

Reputation: 46600

Resizing an image using cv2.resize() should not turn a colored image into grayscale. It simply resizes the image src down to or up to the specified size. To convert an image to grayscale, use cv2.cvtColor(src, cv2.COLOR_BGR2GRAY). Your error message also confirms that the resized image has 3 color channels. Here is confirmation that cv2.resize() does not change an image into grayscale.

example

import cv2

image_file = 'assets/color_palette.jpg'

original = cv2.imread(image_file)
cv2.imshow('original', original)

rgb = cv2.cvtColor(original, cv2.COLOR_BGR2RGB)
cv2.imshow('rgb', rgb)

resized = cv2.resize(rgb, (128,128))
cv2.imshow('resized', resized)

key = cv2.waitKey(0)

Upvotes: 2

Neil Houston
Neil Houston

Reputation: 141

You could try something like this for the resize option:

It's important to keep in mind aspect ratio so the image doesn't look skewed or distorted -- so we need calculate the ratio of the new image to the old image

image = cv2.imread(os.path.join("/path","some_image.png"),0) 
Ratio = 100.0 / image.shape[1]
        dimensions = (128, int(image.shape[0] * Ratio))

# perform the actual resizing of the image and show it
resized = cv2.resize(image, dimensions , interpolation = cv2.INTER_AREA)
cv2.imshow("resized", resized)
cv2.waitKey(0)

What's happening in the resize :

The first parameter is the original image that we want to resize. The second argument is the calculated dimensions for the new image that we calculated earlier in the dimensions variable. The third parameter then just tells us which algorithm to use.

If you need to convert the image from BGR to RGB you should be able to do that just after resizing. You should be able to just resize it before converting it

Upvotes: 1

Related Questions