Jason
Jason

Reputation: 4546

How to check and convert image data types in OpenCV using Python

I'm using various methods in OpenCV to preprocess some images. I often get errors relating to the data type when passing objects been methods eg:

import cv2
import numpy as np

#import image and select ROI
image1 = cv2.imread('image.png')
roi_1 = cv2.selectROI(image1) # spacebar to confirm selection
cv2.waitKey(0)
cv2.destroyAllWindows()

# preprocesssing
imCrop_1 = image1[int(roi_1[1]):int(roi_1[1]+roi_1[3]), int(roi_1[0]):int(roi_1[0]+roi_1[2])]
grey1 = cv2.cvtColor(imCrop_1, cv2.COLOR_RGB2GRAY)
thresh, bw_1 = cv2.threshold(grey1, 200, 255, cv2.THRESH_OTSU)
canny_edge1 = cv2.Canny(bw_1, 50, 100)

#test=roi_1 # Doesn't work with error: /home/bprodz/opencv/modules/photo/src/denoising.cpp:182: error: (-5) Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored
#test = imCrop_1 # works
#test = grey1 # doesn't work with error above
#test = bw_1 # doesn't work with error above
#test = canny_edge1 # doesn't work with error above

dst = cv2.fastNlMeansDenoisingColored(test,None,10,10,7,21)

# Check object types
type(imCrop_1) # returns numpy.ndarray - would like to see ~ CV_8UC3 etc.
type(grey1) # returns numpy.ndarray

Presently I just use trial and error, is a there a more methodical approach that I can use for checking and converting between different object types?

Upvotes: 0

Views: 10146

Answers (1)

ZdaR
ZdaR

Reputation: 22964

You are probably using wrong method, for this purpose, you may also get a hint from the method name you are using, as per documentation of cv2. fastNlMeansDenoisingColored:

src – Input 8-bit 3-channel image.

dst – Output image with the same size and type as src .

So, if want to use cv2. fastNlMeansDenoisingColored then you need to convert the src mat to a 3-channel matrix which can be done as:

cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)

But if you have gray-scale image, then you may use cv2.fastNlMeansDenoising, which accepts the both single channel and three channel as source mats, and save the step for converting the image.

You can also use img.shape to check the number of channels for a given matrix. it would return (100, 100) for a gray-scale matrix, (100, 100, 3) for 3-channel matrix and (100, 100, 4) for 4-channel matrix. You can also get the type of matrix using img.dtype

Upvotes: 2

Related Questions