This is my code for building a linear classifier for images and cv2.resize() is throwing error while converting the image from original size to (32,32)
import numpy as np
import cv2
labels = ["dog","cat","panda"]
np.random.seed(1)
W = np.random.randn(3,3072)
b = np.random.randn(3)
orig = cv2.imread("panda_00001.png")
image = cv2.resize(orig,(32,32)).flatten()
scores = W.dot(image) + b
for (label,score) in zip(labels,scores):
print("[INFO] {}:{:.2f}".format(label,score))
cv2.putText(orig,"Label:{}".format(labels[np.argmax(scores)]),(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.9,(0,255,0),2)
cv2.imshow("Image",orig)
cv2.waitkey(0)
Getting this error on execution
Traceback (most recent call last):
File "linearclassifier.py", line 11, in <module>
image = cv2.resize(orig,(32,32)).flatten()
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3929: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
Your picture path seems to be wrong or invalid.
It's always good practice to integrate a null check to the read picture in your script:
eg:
import cv2
...
img = cv2.imread("myImage.jpg")
if (img.size == 0):
# error handling or throw exception here!
# do stuff with image here
Related
Following code:
img = np.array([[[1,2,4]]])
cv2.subtract(img, tuple([1.0]))
Results in error:
Traceback (most recent call last): File "", line 1, in
cv2.error: OpenCV(4.4.0)
C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-nxx381if\opencv\modules\core\src\arithm.cpp:671:
error: (-215:Assertion failed) type2 == CV_64F && (sz2.height == 1 ||
sz2.height == 4) in function 'cv::arithm_op'
If I change the img to:
img = np.array([[[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4]]])
Then it works correctly
In my case I have images of different sizes mono and color and I want to subtract constant value with saturation. The Shapes are HxWx1 or HxWx3 (different datatypes)
How to correctly use cv2.subtract for such cases ?
Edit:
I would like to keep high performance and avoid to allocate temporary arrays / types conversions
You can just subtract a constant value from a numpy array:
img = np.array([[[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4]]])
img_new=img-1
or if you want to use cv2.substract:
constant = 3
img_new_2=cv2.subtract(img, constant*np.ones(img.shape).astype(type(img[0,0,0])))
edit:
if you want to show this image using opencv you have to convert it to a valid type.
cv2.imshow("window", img_new_2.astype(np.int8))
cv2.waitKey(0)
cv2.destroyAllWindows()
I want to augment images inside a folder. I also want to keep the names of images the same after augmentation in a different folder. How can I do this using OpenCV?
# Defining path
INPUT_IMG_DIR = 'NORMAL'
OUTPUT_AUG_DIR = 'AUGMENT'
seq = iaa.Sequential([iaa.Affine(rotate=5)
# iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5),
# iaa.Multiply((0.5, 1.5), per_channel=0.5),
# iaa.Add((-10, 10), per_channel=0.5)
])
for image in os.listdir(INPUT_IMG_DIR):
image = image
print(image)
print(len(image))
print(type(image))
image = cv2.imread(image)
seq_det = seq.to_deterministic()
image_aug = seq.augment_images(image)
print(image_aug)
cv2.imwrite(OUTPUT_AUG_DIR, image, image_aug)
This code is not working for me. It is throwing error like this,
NORMAL_IMG_0.jpeg
<class 'str'>
None
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-28-b6ca6f4c6834> in <module>
9 image_aug = seq.augment_images(image)
10 print(image_aug)
---> 11 cv2.imwrite(OUTPUT_AUG_DIR, image, image_aug)
error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
replace:
cv2.imwrite(OUTPUT_AUG_DIR, image, image_aug)
with:
cv2.imwrite(os.path.join( OUTPUT_AUG_DIR, image), image_aug)
When I finished the coding, 215:Assertion failed happened, and I think there is no wrong code, but I couln't solve it. How could I solve this problem?
import urllib.request as req
url = "http://uta.pw/shodou/img/28/214.png"
req.urlretrieve(url, "test.png")
import cv2
img = cv2.imread("test.png")
print(img)
%matplotlib inline
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("test.jpg")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
Error:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-11-0f580eb5ee11> in <module>
6 import cv2
7 img = cv2.imread("test.jpg")
----> 8 plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
9 plt.show()
error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
You are getting above error because of below line:
img = cv2.imread("test.jpg")
Your image is actually a PNG file, not JPG file. So, replace above line to img = cv2.imread("test.png").
this is the basic code from opencv-python documentation:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('simple.jpg',0)
# Initiate STAR detector
orb = cv2.ORB()
# find the keypoints with ORB
kp = orb.detect(img,None)
# compute the descriptors with ORB
kp, des = orb.compute(img, kp)
# draw only keypoints location,not size and orientation
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
plt.imshow(img2),plt.show()
and it gives me this error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 18, in <module>
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
error: ..\..\..\..\opencv\modules\features2d\src\draw.cpp:115: error: (-215) !outImage.empty() in function cv::drawKeypoints
i have to mention this error happens in opencv-PYTHON, can you help me out please? struggling really to make it work
i've found the solution
it couldn't find the image
i changed
img = cv2.imread('simple.jpg',0)
to
img = cv2.imread('c:\\python27\\sample.jpg', cv2.IMREAD_GRAYSCALE)
and it worked
note that the image i used for the sample image was one of my own grayscale images.
i started on a project which inputs 2 images and detect the keypoints using sift and then checking the similarity of the 2 images
i actually completed the project without converting the image files to greycode but later i understood that converting images to grey code and then comparing gives more accurate results
so i wrote the code to convert the image to greycode
but i am facing a problem
import cv2
import easygui
import sys
from matplotlib import pyplot as plt
print "image 1 :",sys.argv[1]
print "image 2 :",sys.argv[2]
print "******** comparing images please wait *********"
file1=sys.argv[1]
file2=sys.argv[2]
img1 = cv2.imread(file1,0)#queryImage
img2 = cv2.imread(file2,0)#trainImage
gray_image1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray_image2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
i am getting an error
image 1 : taj1.jpg
image 2 : taj2.jpg
******** comparing images please wait *********
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /root/opencv-3.3.0/opencv-3.3.0/modules/imgproc/src/color.cpp, line 10638
Traceback (most recent call last):
File "image_similarity.py", line 14, in <module>
gray_image1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
cv2.error: /root/opencv-3.3.0/opencv-3.3.0/modules/imgproc/src/color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cvtColor
how can i resolve it
thanks in advance
You don't need to convert it, if you load it as you do.
img1 = cv2.imread(file1,0)#queryImage
img2 = cv2.imread(file2,0)#trainImage
Second parameter=0 means you load it as gray scale image.