I am working on pre-trained vgg16 model, for that I need to have input size of image file to be (224,224,3).
The code I am working on is:
JavaScript
x
16
16
1
from tensorflow.keras.preprocessing import image
2
import cv2
3
import matplotlib.pyplot as plt
4
5
img = image.load_img('abc.jpg',target_size=(224,224))
6
img = image.img_to_array(img)
7
8
print(img.shape)
9
## output : (224,224,3)
10
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
11
#plt.imshow(img_grey)
12
13
th3 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
14
plt.figure(figsize=(20,10))
15
plt.imshow(th3)
16
JavaScript
1
10
10
1
error Traceback (most recent call last)
2
<ipython-input-88-2a8a27b965ed> in <module>
3
17 #plt.imshow(img_grey)
4
18
5
---> 19 th3 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
6
20 plt.figure(figsize=(20,10))
7
21 plt.imshow(th3)
8
9
error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/thresh.cpp:1627: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'adaptiveThreshold'
10
Help me in resolving the issue.
Advertisement
Answer
The error says the solution: src.type() == CV_8UC1
meaning you need to set your image type to the uint8
source
So if you redefine your img
variable:
JavaScript
1
2
1
img = image.img_to_array(img, dtype='uint8')
2
Problem will be solved but I have a question.
Why do you define the below statement?
JavaScript
1
2
1
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
2
How do you know load_img
loads the image in BGR
fashion?
We know opencv loads the image cv2.imread
in BGR
fashion.
The statement is wrong, since load_img
loads the image in RGB
format source
Therefore the correct statement will be:
JavaScript
1
2
1
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
2
or you can do:
JavaScript
1
2
1
img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))
2
Correct Code:
JavaScript
1
16
16
1
from keras.preprocessing import image
2
import cv2
3
import matplotlib.pyplot as plt
4
5
img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))
6
img = image.img_to_array(img, dtype='uint8')
7
8
print(img.shape)
9
## output : (224,224,3)
10
#plt.imshow(img_grey)
11
12
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
13
plt.figure(figsize=(20,10))
14
plt.imshow(th3, cmap="gray")
15
plt.show()
16