Reputation: 370
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?
Upvotes: 14
Views: 63665
Reputation: 2020
It may be easier to initialize new numpy array with initial image as source and dtype=np.uint8
:
import numpy as np
img = cv2.imread('path//to//image//file')
img = np.array(img, dtype=np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Upvotes: 7
Reputation: 337
imagine you have a function called preprocessing() that preprocess your images with cv2, if you try to apply it as:
data = np.array(list(map(preprocessing,data)))
it won't work and that because np.array creates int64and you are trying to assign np.uint8 to it, what you should do instead is adding dtype parameter as follow:
data = np.array(list(map(preprocessing,data)), dtype = np.uint8)
Upvotes: -1
Reputation: 370
The error occured because the datatype of numpy array returned by cv2.imread
is uint8
, which is different from the datatype of numpy array returned by np.full()
. To make the data-type as uint8, add the dtype
parameter-
img = np.full((100,80,3), 12, dtype = np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Upvotes: 4
Reputation: 2307
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)
Upvotes: 22