how to call multiple image with opencv - opencv

I am using this line of code to call my image in python
(img = cv2.imread("frame12160.jpg")
but I can just call one image once a time how can I call multiple images every time and thanks in advance

You can only read one image at a time using cv2.imread(). If you want to read in multiple images, try using the os package and save the images into a list:
import cv2
import os
my_images = []
os.chdir('/home/stephen/Desktop/images/')
for path in os.listdir(os.getcwd()):
img = cv2.imread(path)
my_images.append(img)

Related

jpg images without extension aren't displayed

from kivy.uix.image import Image
self.img = Image(source="image") # This works when image is an PNG image
self.img = Image(source="image.jpg") # This works when image.jpg is a JPG image
self.img = Image(source="image") # This doesn't work when image is a JPG image
I need to specify images without extention for the app to be generic (working with more image types). Can I achieve it somehow?
Kivy is using "imghdr" to determine the image type here, and as a fallback it uses the file extension here.
That explains why the image loads fine when it has a file extension, even though "imghdr" can't find the file type in the file's content.
I tested on a list of JPEG files, and each time "imghdr" was able to detect the file type each time. That is done here im imghdr. Notably, "imghdr" does not consider the file extension.
$ python
>>> import os, imghdr
... for f in os.listdir('.'):
... print('%s -- %s' % (f, imghdr.what(f)))
Maybe the JPEG file is missing the "JFIF" or "Exif" string that imghdr is looking for? You could use hexedit to see if one of those string is present at Byte 6 of the image file.

Converting JPG to TIFF using Opencv

I want to convert a jpg image to tiff.
I tried to do it with opencv with python.
import cv2
image = cv2.imread("image.jpg")
retval, buf = cv2.imencode(".tiff", image)
cv2.imwrite("out.tiff")
And I have this:
Process finished with exit code 136 (interrupted by signal 8: SIGFPE)
I referred this link
But I couldn't make it work.
Any help would be appreciated.
For me this version worked without errors:
import cv2
image = cv2.imread("image.jpg")
cv2.imwrite("out.tiff", image)
Why do you need the imencode? Using that gives the same resulting file for me, just creates a temporary memory buffered, already TIFF-compressed version of the image:
retval, buf = cv2.imencode(".tiff", image)
with open('out2.tiff', 'wb') as fout:
fout.write(buf.tostring())

Saving an image to another folder of my choice (with "~") using OpenCV

I am a few images in the "Downloads" folder. I want to save the images to a particular folder named "unclassified" using OpenCV. I have already seen the question OpenCV - Saving images to a particular folder of choice and from that I have tried this particular code:
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = '~/Downloads/unclassified'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
This works on Windows but it didn't work on Ubuntu (I am working on a Ubuntu 16.04) when I wrote:
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
The code returned False on Ubuntu. What should I do to solve this error?
You can use something like that:
cv2.imwrite(os.path.expanduser(os.path.join(path , 'waka.jpg')), img)
The problem is with the "~". os.path.expanduser(...) will change that with the appropriate path.

cv2.imshow() function is opening a window that always says not responding - python opencv

I am trying to run a very simple program. To open and jpg file and display it using the opencv library for python. Initially it all worked fine but now it just opens a window which doesn't show the image but says 'not responding'. I need to go to the task manager and close it!
from numpy import *
import matplotlib as plt
import cv2
img = cv2.imread('amandapeet.jpg')
print img.shape
cv2.imshow('Amanda', img)
You missed one more line:
cv2.waitKey(0)
Then the window shows the image until you press any key on keyboard. Or you can pass as following:
cv2.waitKey(1000)
cv2.destroyAllWindows()
Here, window shows image for 1000 ms, or 1 second. After that, the window would disappear itself. But in some cases, it won't. So you can forcefully destroy it using cv2.destroyAllWindows()
Please read more tutorials first : http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
None of the answers here worked in MacOS. The following works:
Just add a cv2.waitKey(1) after cv2.destroyAllWindows().
Example:
import cv2
image = cv2.imread('my_image.jpg')
cv2.imshow('HSV image', hsv_image); cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
The solution that worked for me:
Switch from inline graphics to auto. It worked both in Spyder and in Jupyter notebooks.
To change Spyder setting:
Go to Tools > Preferences > IPhyton console > Graphics > Backend: Automatic
(Change backend from Inline to Automatic)
To change Notebook setting:
Enter command:
%matplotlib auto
Some background for my case (for those who may be quick to judge):
It used to work fine: I could open an image, it would load, and it would be responsive (doesn't say "Not responding", can close, focus, etc.) Then I installed some packages and ran some demo notebooks that apparently messed up some settings (Spyder open files were reset too).
I tried adding waitKey(1) (and 0, 30, 1000, etc values too). It made the image load, at least. But the image frame was "Not Responding": didn't refresh, couldn't close, didn't come to top, etc. Had to close using cv2.destroyAllWindows().
Note that everything worked fine during the duration of waitKey. I put this in a loop that shows the same image in the same named window and waits for a few seconds. During the loop everything works fine. As soon as the loop ends, the image window is "Not responding" (which looks like a GUI thread issue). I tried using cv2.startWindowThread(), and didn't make any difference.
Finally, changing from Inline graphics to Auto brought everything back to order.
I've been working with opencv 3.2 and matplotlib too recently and discovered (through trial and error of commenting out lines) that the import of pyplot from matplotlib has some sort of interference with the cv2.imshow() function. I'm not sure why or how it really works but in case anyone searches for this issue and comes across this old forum, this might help. I'm working to try to find a solution around this interference bu
I did also face the same issue. I am running through command line python prompt in centos 7 with the following code
>> import cv2, numpy as np
>> cap=cv2.VideoCapture(0)
>> img=cap.read()
>> cap.release()
>> cv2.imshow('image',img[1])
>> cv2.waitKey(0)
>> cv2.destroyAllWindows()
>> cv2.waitKey(1)
Even then the problem persisted and didn't solve. So I added
>> cv2.imshow('image',img[1])
Adding this did close the image window.Running the command again would create a new instance. Hope you can try if you still face any issues.
The cv2.imshow() function always takes two more functions to load and close the image. These two functions are cv2.waitKey() and cv2.destroyAllWindows(). Inside the cv2.waitKey() function, you can provide any value to close the image and continue with further lines of code.
# First line will provide resizing ability to the window
cv.namedWindow('Amanda', cv.WINDOW_AUTOSIZE)
# Show the image, note that the name of the output window must be same
cv.imshow('Amanda', img)
# T0 load and hold the image
cv.waitKey(0)
# To close the window after the required kill value was provided
cv.destroyAllWindows()
Hoping that you will get the image in a separate window now.
I've installed opencv-contrib-python library instead of opencv-python and now cv2.imshow() function works as expected.
If you have used python notebooks then there is a problem in using cv2.waitKey(0) and cv2.destroyallwindows() in Unix based system to run a program of opencv.
I have an alternative method which would prevent from freezing your image
Steps: -Copy the code from python notebooks and create new filename.py and paste it
- Open terminal
- cd path/to/file
- source activate VirtualEnvironment
- python filename.py
This will run code directly from terminal. Hope this helps you. Example Link: https://youtu.be/8O-FW4Wm10s
I was having this same error until I added the below lines of code. For the waitKey, you can input figures above 0(i.e 1, 100 and above). It serves as the delay time for the window and it is in milliseconds.
----> cv2 waitKey(0)
----> cv2 destroyAllWindows()
I found that i had a breakpoint on the
cv2.waitkey()
funtion. removing that fixed the issue for me
As I tried all solutions mentioned above, it works for displaying an image but in my case, I want to display the video not just the single image in the window, So to solve the problem added
k=cv2.waitkey(10)
if k == 27:
break
after cv2.imshow('title',img)

Error during image decoding (imdecode)

I use puthon 2.7, windows 7 and opencv 2.4.6. and I try to run the following code:
https://github.com/kyatou/python-opencv_tutorial/blob/master/08_image_encode_decode.py
#import opencv library
import cv2
import sys
import numpy
argvs=sys.argv
if (len(argvs) != 2):
print 'Usage: # python %s imagefilename' % argvs[0]
quit()
imagefilename = argvs[1]
try:
img=cv2.imread(imagefilename, 1)
except:
print 'faild to load %s' % imagefilename
quit()
#encode to jpeg format
#encode param image quality 0 to 100. default:95
#if you want to shrink data size, choose low image quality.
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]
result,encimg=cv2.imencode('.jpg',img,encode_param)
if False==result:
print 'could not encode image!'
quit()
#decode from jpeg format
decimg=cv2.imdecode(encimg,1)
cv2.imshow('Source Image',img)
cv2.imshow('Decoded image',decimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
I keep getting the following error:
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY), 90]
AttributeError: 'module' object has no attribute 'IMWRITE_JPEG_QUALITY'
I have tried a lot of things: reinstall opencv, convert cv2 to cv code and searched different forums but I keep getting this error. Am I missing something? Is there someone who can run this code without getting the error?
BTW: Other opencv code (taking pictures from webcam) runs without problems....
At the moment I save the image to a temp JPG file. Using the imencode function I want to create the jpg file in the memory.
Thanks in advance and with best regards.
The problem is not in your code, it should work, but it is with your OpenCV Python package. I can't tell you why is raising that error, but you can avoid it by changing the line of the encode_param declaration by this one:
encode_param=[1, 90]

Resources