I am trying to convert an image from BGR to grayscale format using this code:
img = cv2.imread('path//to//image//file')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
This seems to be working fine: I checked the data type of the img
variable which turns out to be numpy ndarray and shape to be (100,80,3)
. However if I give an image of a native numpy ndarray data type with same dimensions of the input of the cvtColor
function, it gives me the following error:
Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp, line 11109
cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp:11109: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cv::cvtColor
The code for the second case is (making a custom np.ndarray
over here):
img = np.full((100,80,3), 12)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Can anyone clarify what is the reason for this error and how to rectify it?
The conversion from a RGB image to gray is done with: cvtColor(src, bwsrc, cv::COLOR_RGB2GRAY); More advanced channel reordering can also be done with cv::mixChannels.
OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.
Convert BGR and RGB with OpenCV function cvtColor() Various color spaces such as RGB, BGR, HSV can be mutually converted using OpenCV function cvtColor() . Refer to the following document for the value to be specified for the parameter code . When code is cv2. COLOR_BGR2RGB , BGR is converted to RGB.
So to convert the color image to grayscale we will be using cv2. imread("image-name. png",0) or you can also write cv2. IMREAD_GRAYSCALE in the place of 0 as it also denotes the same constant.
This is because your numpy array is not made up of the right data type. By default makes an array of type np.int64
(64 bit), however, cv2.cvtColor()
requires 8 bit (np.uint8
) or 16 bit (np.uint16
). To correct this change your np.full()
function to include the data type:
img = np.full((100,80,3), 12, np.uint8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With