Hi friends i just now installed opencv and checking the basic code but it results in error. The code is
import numpy as np
import cv2
img=cv2.imread('C:\Users\Pravin\Desktop\a.jpeg',1)
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.Waitkey(10000)
cv2.imshow('cv2.WINDOW_NORMAL',img)
cv2.destoryAllWindows()
The error for cv2.imshow() is
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
cv2.imshow('image',img)
error: ..\..\..\src\opencv\modules\highgui\src\window.cpp:261: error: (-215)
size.width>0 && size.height>0
It was very helpful to me with your answer.
Thanks in advance
Most likely, the imread call didn't succeed. Make sure the image "C:\Users\Pravin\Desktop\a.jpeg" exists. (The extension .jpeg seems unusual, maybe it has to be .jpg?)
Also, as Hyperboreus suggests, please, try using forward slashes in the filename "C:/Users/Pravin/Desktop/a.jpg", or escape backslashes
"C:\\Users\\Pravin\\Desktop\\a.jpg"
The error says that the image you opened doesn't satisfy the condition height > 0 and width > 0. This may have several reasons.
Most of the times, it is due to an inexistent image address given in imread.
Sometimes it may be also because the complier failed to load the image. For example, if you write some random strings in notepad and save the file as a.jpg, the compiler may not be able to load it.
Try this...
import numpy as np
import cv2
img = cv2.imread('E:/Images/ece/1.png',1)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
For me it worked when i just changed jpeg to jpg
Try this, may be it will work
import numpy as np
import cv2
img=cv2.imread('C:\Users\Pravin\Desktop\a.jpg',1) #changed image format to jpg
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.Waitkey(10000)
cv2.imshow('cv2.WINDOW_NORMAL',img)
cv2.destoryAllWindows()
It is because, python compiler cannot find the image in the place. if you copy the image in the python working directory and do this. it worked for me.
# keep image in the current working directory
img=cv2.imread('roi.jpg',1)
cv2.imshow('image',img)
Related
I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:
import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random
# (0, 1) is N
SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels
MIN_LENGTH = 150 # pixels
PROJECT_PATH = 'C:\\cimtrack_v1'
im = Image.open(PROJECT_PATH + '\\ST.jpg')
I end up with the following errors:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\cimtrack_v1\PythonApplication1\dr\trajgen.py", line 19, in <module>
im = Image.open(PROJECT_PATH + '\\ST.jpg')
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2020, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
Why is it so and how may I fix it?
As suggested, I have used the Pillow installer to my Python 2.7. But weirdly, I end up with this:
>>> from PIL import Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PIL
>>> from pil import Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pil
>>> import PIL.Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PIL.Image
>>> import PIL
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PIL
All fail!
I had a same issue.
from PIL import Image
instead of
import Image
fixed the issue
So after struggling with this issue for quite some time, this is what could help you:
from PIL import Image
instead of
import Image
Also, if your Image file is not loading and you're getting an error "No file or directory" then you should do this:
path=r'C:\ABC\Users\Pictures\image.jpg'
and then open the file
image=Image.open(path)
In my case.. I already had "from PIL import Image" in my code.
The error occurred for me because the image file was still in use (locked) by a previous operation in my code. I had to add a small delay or attempt to open the file in append mode in a loop, until that did not fail. Once that did not fail, it meant the file was no longer in use and I could continue and let PIL open the file. Here are the functions I used to check if the file is in use and wait for it to be available.
def is_locked(filepath):
locked = None
file_object = None
if os.path.exists(filepath):
try:
buffer_size = 8
# Opening file in append mode and read the first 8 characters.
file_object = open(filepath, 'a', buffer_size)
if file_object:
locked = False
except IOError as message:
locked = True
finally:
if file_object:
file_object.close()
return locked
def wait_for_file(filepath):
wait_time = 1
while is_locked(filepath):
time.sleep(wait_time)
first, check your pillow version
python -c 'import PIL; print PIL.PILLOW_VERSION'
I use pip install --upgrade pillow upgrade the version from 2.7 to 2.9(or 3.0) fixed this.
In my case, the image was corrupted during download (using wget with github url)
Try with multiple images from different sources.
python
from PIL import Image
Image.open()
Often it is because the image file is not closed by last program.
It should be better to use
with Image.open(file_path) as img:
#do something
In my case, it was because the images I used were stored on a Mac, which generates many hidden files like .image_file.png, so they turned out to not even be the actual images I needed and I could safely ignore the warning or delete the hidden files. It was just an oversight in my case.
Just a note for people having the same problem as me.
I've been using OpenCV/cv2 to export numpy arrays into Tiffs but I had problems with opening these Tiffs with PIL Open Image and had the same error as in the title.
The problem turned out to be that PIL Open Image could not open Tiffs which was created by exporting numpy float64 arrays. When I changed it to float32, PIL could open the Tiff again.
If you are using Anaconda on windows then you can open Anaconda Navigator app and go to Environment section and search for pillow in installed libraries and mark it for upgrade to latest version by right clicking on the checkbox.
Screenshot for reference:
This has fixed the following error:
PermissionError: [WinError 5] Access is denied: 'e:\\work\\anaconda\\lib\\site-packages\\pil\\_imaging.cp36-win_amd64.pyd'
Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.
In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.
This error can also occur when trying to open a multi-band image with PIL. It seems to do fine with 4 bands (probably because it assumes an alpha channel) but anything more than that and this error pops out. In my case, I fixed it by using tifffile.imread instead.
I had the same issue. In my case, the image file size was 0(zero). Check the file size before opening the image.
fsize = os.path.getsize(fname_image)
if fsize > 0 :
img = Image.open(fname_image)
#do something
In my case the image file had just been written to and needed to be flushed before opening, like so:
img_file.flush()
img = Image.open(img_file.name))
For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.
For whoever reaches here with the error colab PIL UnidentifiedImageError: cannot identify image file in Google Colab, with a new PIL versions, and none of the previous solutions works for him:
Simply restart the environment, your installed PIL version is probably outdated.
For me it was fixed by downloading the image data set I was using again (in fact I forwarded the copy I had locally using vs-code's SFTP). Here is the jupyter notebook I used (in vscode) with it's output:
from pathlib import Path
import PIL
import PIL.Image as PILI
#from PIL import Image
print(PIL.__version__)
img_path = Path('PATH_UR_DATASET/miniImagenet/train/n03998194/n0399819400000585.jpg')
print(img_path.exists())
img = PILI.open(img_path).convert('RGB')
print(img)
output:
7.0.0
True
<PIL.Image.Image image mode=RGB size=158x160 at 0x7F4AD0A1E050>
note that open always opens in r mode and even has a check to throw an error if that mode is changed.
In my case the error was caused by alpha channels in a TIFF file.
I'll add my particular case.
I was processing images uploaded through multipart/form-data using AWS API Gateway. When I was uploading my images, that had not been giving this error locally, I was observing UnidentifiedImageError exception thrown by PIL when loading uploaded image. In order to fix this error I had to add multipart/form-data within settings of service.
Im working in Google colab, and in had same problem.
UnidentifiedImageError: cannot identify image file '/content/drive/MyDrive/Python/test.jpg'
The problem is that the default version of PIL (as today 24/11/2022) in colab is 9.3.0; but when you do !pip install pillow the version that is updated is 7.1.2.
So, what I did was open a new colab notebook and NOT pip pillow. It worked.
I am trying to detect humans in images using the haarcascade full body algorithm using OpenCv in Python.
when i consider using it on a single image, I face no issues.
import numpy as np
import cv2 as cv
body_cascade = cv.CascadeClassifier(r'...\haarcascade_fullbody.xml')
image = cv.imread(r'...\image.jpg')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(image,(x,y),(x+w,y+h),(255,0,0),3)
But, when I try to use the same program and iterate over several images at once, I get a cryptic OpenCv error. I have some images in a folder and I want to separate images with humans in them from those that don't. I wrote the following:
import os
for file in os.walk(r'...\Folder'):
file=str(file)
im=cv.imread(file)
gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(im,(x,y),(x+w,y+h),(255,0,0),3)
if(body.size >= 0):
print('okay')
else:
print('Not okay')
But I get the following error :
error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper<struct cv::Set<3,4,-1>,struct cv::Set<1,-1,-1>,struct cv::Set<0,2,5>,2>::CvtHelper'
for the line gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
I am unable to understand what the error is and why the same code that works when taking individual images is working but not the case when iterating through a folder. Do I need to resize the images ?
Also, I tried with keeping just one image in the folder, on which the code had worked before, still doesn't work.
Doc, it seems like OpenCV fails to locate the image. What happens if you're using full paths instead of relative ones? (and what are the three dots there "..." ?)
please dump the file that you read back to disc for debugging purposes and I think you'll be surprised.
I am trying to read and display an image in Python OpenCV.
Executing the following code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('dumb.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Results in the following error:
cv2.error:
C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\highgui\src\window.cpp:325: error: (-215) size.width>0 && size.height>0 in function cv::imshow
How to solve this?
NOTE: I have all the prerequisites needed to execute this (python 2.7, opencv 3.3
matplotlib, numpy)
If you are trying to display OpenCV image using matplotlib, use the code below.
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline # if you are running this code in Jupyter notebook
# reads image 'opencv-logo.png' as grayscale
img = cv2.imread('/path_to_image/opencv-logo.png', 0)
plt.imshow(img, cmap='gray')
there is a tutorial on http://docs.opencv.org/3.1.0/dc/d2e/tutorial_py_image_display.html
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('/path_to_image/messi5.jpg',0)
# show image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
use an absolute path to the image then you have no path problems
https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow
I have written a short post to learn image reading with OpenCV in Python. You can see the below code snippet with the description.
import cv2 #Import openCV
import sys #import Sys. Sys will be used for reading from the command line. We give Image name parameter with extension when we will run python script
#Read the image. The first Command line argument is the image
image = cv2.imread(sys.argv[1]) #The function to read from an image into OpenCv is imread()
#imshow() is the function that displays the image on the screen.
#The first value is the title of the window, the second is the image file we have previously read.
cv2.imshow("OpenCV Image Reading", image)
cv2.waitKey(0) #is required so that the image doesn’t close immediately. It will Wait for a key press before closing the image.
To read an image with OpenCV you have to use the following synthax. If it doesn't work, there is a problem with the installation.
import cv2
image = cv2.imread('path_of_the_image.png')
cv2.imshow('img', image)
cv2.waitKey(0)
You didn't post the error it gives..
EDIT: I don't understand the negative points...for what ??
The reason for this error message is that cv2.imread() was unable to find the image where it was looking for the image. This should work if you add the full path to the image, like
img = cv2.imread('/home/foo/images/dumb.jpg',cv2.IMREAD_GRAYSCALE)
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# Hide grid lines
fig, ax = plt.subplots(figsize=(10,10))
ax.grid(False)
im=cv2.imread('./my_images.jpg')
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
plt.show()
It use cv2.COLOR_BGR2RGB because it convert default settings of OpenCV which using BGR to RGB format
Use 0 rather than cv2.IMREAD_GRAYSCALE and I would hard code the location of the file rather than refer to it like that for example if it was on the C drive put 'C:\\Filename.jpg'
Try this one :
import cv2 as cv #openCV-3.4.1
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('image path and name .file type ',0)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
It looks like your code is fine. The problem seems to be in the dimension of image that is being provided in the parameters. The error code says: size > 0 && width > 0. This condition is not meeting properly. Either dimension size or width is less than zero. You may want to check any other image and try with that.
i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:
/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
error: (-215) size.width>0 && size.height>0 in function imshow.
and the code is:
import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
The image fails to load (probably because you forgot the leading / in the path). imread then returns None. Passing None to imshow causes it to try to create a window of size 0x0, which fails.
The poor error handling in cv probably owes to its quite thin wrapper layer on the C++ implementation (where returning NULL on error is a common practice).
it's the path which is causing the problem, i had the same problem but when i gave the full path of the image it was working perfectly.
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.
sudo pip install pypng
Use r in the code where you specified the file address.
For Example:
import cv2
img = cv2.imread(r'D:\Study\Git\OpenCV\resources\lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)
r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.
In my case, I had forgotten to change the working directory of my terminal to that of my code+testImage. Hence, it failed to find the image there.
Finally, this is what worked for me:
I saved the image and Python file on Desktop. I changed my cmd directory to it,
cd Desktop
And then checked for my file:
ls
And this was my code that worked:
import cv2
import numpy as np
im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds
I am also getting a similar error, so instead of opening a new question, I thought maybe it would be a good idea to gather it all here since there's already some helpful answers...
My code (textbook code to open a video using OpenCV in Python):
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file)
if not cap.isOpened():
print("Error opening Video File.")
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
The reason why I am dumbfounded is that I am getting the same error - BUT - the video is actually played... When running the code the Python interpreter opens up an instance of Python running the video. Once the video ends, it breaks out of the loop, closes the video and throws the error:
Traceback (most recent call last):
File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in
cv.imshow('frame',frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wwma2wne\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
I'd appreciate any input!
**
EDIT: How I fixed my error!
**
I encased my code in a try/except like this:
# Import required libraries
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
if not cap.isOpened():
print("Error opening Video File.")
try:
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
except:
print("Video has ended.")
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I'd still appreciate any input on why this error popped up even though the video played fine, and why the try/except eliminated it.
Thank you!
One of the reasons, this error is caused is when there is no file at the path specified. So, a good practice will be to verify the path like this ( If you are on a linux based machine ):
ls <path-provided-in-imread-function>
You will get an error if the path is incorrect or the file is missing.
While reading the image file, specifying the color option should solve this,
for example:
image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)
adding the cv2.IMREAD_COLOR should solve this
This problem happened to me when i just failed to write the extension of the image.
Please check if you forgot to write the extension or any other part of the full path to the image.
Remember, extension is required whether you are printing image using OpenCV or Mathplotlib.
I solve it by using this code
os.chdir(f"{folder_path}")
It is because the image is not loaded. For me at VScode the relative path was problem but after copying the file path from VSCode itself the problem was solved.
I had the same problem too, on VSCode. Tried running the same code on Notepad++ and it worked. To fix this issue on VSCode, don't forget to open the folder that you're working in on the left pane. This solved my issue.
I am a beginner at opencv and python.
I have just installed opencv2.4.9 and enthought canopy-32bit. I am getting error for the following:
import cv2
image = cv2.imread('Lena.jpg')
cv2.imwrite('Mypic',image)
This is what I get:
c:\users\nam\appdata\local\temp\tmpokspbt.py in <module>()
3
4 image = cv2.imread('Lena.jpg')
----> 5 cv2.imwrite('Mypic',image)
error: ..\..\..\..\opencv\modules\highgui\src\loadsave.cpp:275: error: (-2) could not find a writer for the specified extension in function cv::imwrite_
you need to give an extension to imwrite(), so it knows, how to save(compress) it.
cv2.imwrite('Mypic.png',image)
# jpg,bmp,png,ppm,pgm,tiff supported 'out-of-the-box,
# webp,jp2 depending on if you compiled in the resp. 3rd party support
# no gif or tga.
You need to make sure you have the image type within the string you give to the imwrite().
imwrite() dose not have a default method to save, thus it is required within the name you give to it.
instead of :
cv2.imwrite('Mypic',image)
you need to write :
cv2.imwrite('Mypic.The_format_you_want_to_save',image)
As an example:
cv2.imwrite('Mypic.jpg',image)
Add an extension for the output file like .jpg, .png, etc based on the application.
For example in this case you could use,
import cv2
image = cv2.imread('Lena.jpg')
cv2.imwrite('Mypic.jpg',image)
I could solve this problem by simply adding the extension '.jpg' etc at the end of the image and it worked for me!