I've tried using all the approaches already mentioned here but none of them are working for whatever reason.
import cv2
import os
import glob
path = '.../Desktop/Plot/'
os.chdir(path)
# video_name = 'video.avi'
width=640
height=400
size = (width,height)
img_array = []
for filename in sorted(glob.glob(path+'*.png')):
img = cv2.imread(path+filename+'.png')
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
I don't see any thing particularly wrong with this code but all it does is put a 6 kb file in the folder that doesn't play.
I see many instakes in code.
1) most systems doesn't know path ... which you have in '.../Desktop/Plot/' and it may need to be .. or ../.. instead of ...
2) you use relative path - '.../Desktop/Plot/' and when you use os.chdir() to change directory then relative path with current folder will create path
../Desktop/Plot/../Desktop/Plot/
and it is not correct path.
3) glob.glob(path+'*.png') will create filenames with path and .png but you add path and .png to read image in imread() - so you get filename with double path and dougle extension
../Desktop/Plot/../Desktop/Plot/filename.png.png
use print(path+filename+'.png') to see what you try to read.
BTW: cv2 doesn't raise error when it can't read image but it return empty frame/image and you can get error when it try to modify empty image.
4) if images have size different than 640x400 then it will create empty video because it doesn't resize images when you save in video. You have to manually resize images before save in file
img = cv2.resize(img, (width, height))
BTW some decoders don't work with some file extensions - for example 'DIVX' will not save in file with textension .mov
BTW you can do all with one for-loop and without img_array
My version
import cv2
import os
import glob
path = '../Desktop/Plot/'
#print(os.getcwd())
width = 640
height = 400
out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, (width,height))
for filename in sorted(glob.glob(path + '*.png')):
print(filename)
img = cv2.imread(filename)
img = cv2.resize(img, (width, height))
out.write(img)
out.release()
Related
Does anybody know how to upload an image (using filedialog.askopenfile) and then storing the uploaded image to an existing folder on my computer?! All the examples available on the internet require image paths, and i get an error whenever i provide the filepath for the uploaded image, am i doing something wrong?
import cv2
import os
from tkinter.filedialog import askopenfile
filename = askopenfile(title ='open', filetypes=(("PNGs", "*.png"),("JPGs", "*.jpg"), ("GIFs", "*.gif")))
img = cv2.imread(filename)
path = "/Users/mac/desktop/test" # => Folder path
cv2.imwrite(os.path.join(path, img)
I am trying to run a simple example code to write an image using opencv on python3. Code reference:1
import cv2
import os
image_path = r'C:\Users\840g1 touch\Desktop\B2.jpg'
directory = r'C:\Users\840g1 touch\Desktop'
img = cv2.imread(image_path)
os.chdir(directory)
print("Before saving image:")
print(os.listdir(directory))
# Filename
filename = 'savedImage.jpg'
cv2.imwrite(filename, img)
print("After saving image:")
print(os.listdir(directory))
print('Successfully saved')
Image is displaying and everything but the image is not getting saved anywhere. I am using Anaconda on windows. Not sure if the problem is related to the code or my PC.
Any help is much appreciated!
You did not provide a path for imwrite so it writes in your pythons current working directory.
change the line:
cv2.imwrite(filename, img)
to something like:
cv2.imwrite(os.path.join(directory,filename), img)
note:
you can get your current working dir with
os.getcwd()
I am trying to solve a problem in Python where I am needing to convert TIFF images to JPEGs. I have tried using Pillow as well as OpenCV to do this but keep getting errors when I try to convert a TIFF image that has the transparency saved on it. If I save the TIFF and remove the transparency it saves the JPEG successfully. The transparency has to remain on the TIFF. Does anyone know of a solution for this issue? If I could find a way to even save the TIFF without the transparency via a Python script, save as a JPEG, and then delete the TIFF without the transparency that would work too. Any help here would be greatly appreciated. Below are examples of code I have tried that have failed:
import os
from PIL import Image
os.chdir('S:/DAM/Test/Approved/')
# for root, dirs, files in os.walk('S:/DAM/Test/Approved'):
for root, dirs, files in os.walk('.'):
for name in files:
if name.endswith('.tif'):
filename = os.path.join(root, name)
print('These are the files: ', filename)
# img = Image.open(filename).convert('RGB')
img = Image.open(filename)
print('image is open', filename)
img = img.convert('RGB')
print('image should be converted: ', filename)
imageResize = img.resize((2500, 2500))
print('image should be resized: ', filename)
imageResize.save(filename[:-4]+'.jpg', 'JPEG')
print('image should be saved as a jpeg: ', filename)
Here is the error I get when Python tries to open the TIFF with transparency using Pillow:
Exception has occurred: UnidentifiedImageError
cannot identify image file '.\\Beauty Images\\XXX.tif'
File "U:\Python files\image_conversion2.py", line 22, in <module>
img = Image.open(filename)
When I run this code using OpenCV it fails on the same image as well:
img = cv2.imread('S:/DAM/Test/Approved/Beauty Images/XXX.tif')
cv2.imwrite('S:/DAM/Test/Approved/Beauty Images/XXX.jpg', img)
Here is the error I get with this code:
OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
File "U:\Python files\img_convert_new.py", line 19, in <module>
cv2.imwrite('S:/DAM/Test/Approved/Beauty Images/XXX.tif', img)
Here is how to read a CMYKA TIFF with Python Wand, remove the alpha channel, save it to JPG and also convert the image to OpenCV format.
Input:
from wand.image import Image
from wand.display import display
import numpy as np
import cv2
with Image(filename='guinea_pig.tiff') as img:
display(img)
with img.clone() as img_copy:
# remove alpha channel and save as JPG
img_copy.alpha_channel='off'
img_copy.format = 'jpeg'
img_copy.save(filename='guinea_pig.jpg')
display(img_copy)
# convert to opencv/numpy array format and reverse channels from RGB to BGR for opencv
img_copy.transform_colorspace('srgb')
img_opencv = np.array(img_copy)
img_opencv = cv2.cvtColor(img_opencv, cv2.COLOR_RGB2BGR)
# display result with opencv
cv2.imshow("img_opencv", img_opencv)
cv2.waitKey(0)
Resulting JPG:
Thanks to #cgohlke the solution was found! The solution is as follows using imagecodecs. The fullpath variable is the root + '/' + file of the source path.
for root, subdirs, files in os.walk(src):
for file in files:
fullpath = (root + '/' + file)
from imagecodecs import imread, imwrite
from PIL import Image
imwrite(fullpath[:-4] + '.jpg', imread(fullpath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
# The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
# Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
# The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
img = Image.open(fullpath[:-4] + '.jpg') # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
img = img.convert('RGB') # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
imageResize = img.resize((2500, 2500)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
imageResize.save(fullpath[:-4] + '.jpg') # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
I wanted to make a script that will convert images stored in a folder to video.
Here's the code:
import cv2
import numpy as np
import os
import pyautogui
import msvcrt
imageFolder = input('Please enter images folder path: ').replace(chr(34),"")
outputPath = imageFolder+'\Video.avi'
try:
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
while len(images)==0:
imageFolder = input('There are no images in the directory ! Please enter images folder path: ').replace(chr(34),"")
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
print('Creating recording...')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
frame = cv2.imread(os.path.join(imageFolder, images[0]))
height, width, layers = frame.shape
frameRate = 2
video = cv2.VideoWriter(outputPath, fourcc, frameRate, (width,height))
for image in images:
print(f'{int((images.index(image)/len(images))*100)} %', end="\r")
video.write(cv2.imread(os.path.join(imageFolder, image)))
cv2.destroyAllWindows()
video.release()
decision = input('Recording has been created successfully ! Do you want to open it? [Y/N]: ')
if decision.lower() == 'y':
print('Opening file...')
os.startfile(outputPath)
except:
print(f'There was a problem with creating a recording. Check images path: {imageFolder}')
The code works fine when I'm launching that from command line, but after converting that to EXE with pyinstalller (pyinstaller -F ConvertToRecording.py) I'm getting an error like this:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (3
92) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cp
p:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the n
ame of file): C:\Users\MyUser\Documents\Test\20191018_12_45\Video.avi in function
'cv::icvExtractPattern'
Any help appreciated !
I met the same problem. Just go to your OpenCV folder (if you don't have, go here: https://opencv.org/releases/) and find the opencv_videoio_ffmpeg420_64.dll ( I am using 4.20) file. copy it and paste it to your exe direction (same folder).
Then it will work.
Use the os.path module to with paths instead of concatenating strings. This ensures a better cross-platform compatibility. See the manual for a more elaborate explanation of the module.
I am trying to execute this script
from PIL import Image
im = Image.open("image.jpg")
nx, ny = im.size
It is working fine when I run it in python shell
pytesser_v0.0.1]#env python
>>> from PIL import Image
>>> im = Image.open("image.jpg")
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=46x24 at 0x7FA4688F16D0>
but when I put it in a some test.py file and run it like python test.py
I am getting this error
File "test1.py", line 17, in <module>
im = Image.open("image.jpg")
File "/usr/local/python.2.7.11/lib/python2.7/site-packages/PIL/Image.py", line 2309, in open
% (filename if filename else fp))
IOError: cannot identify image file 'image.jpg'
please help me with this issue, Thanks
PS: Earlier I installed PIL from Imaging-1.1.7 setup.py, later I installed Pillow, I think the problem was in the mutual presence of the PIL and Pillow library on the machine.
Seems like PIL library haven't fixed this bug yet.
Here is my solution:
Open image using OpenCV library, then convert it to PIL image
from PIL import Image
import cv2
image_path = 'Folder/My_picture.jpg'
# read image using cv2 as numpy array
cv_img = cv2.imread(image_path)
# convert the color (necessary)
cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
# read as PIL image in RGB
pil_img = Image.fromarray(cv_img).convert('RGBA')
Then you can operate with it as with a regular PIL image object.
Make sure that "image.jpg" is in the same directory as "test1.py".
If it isn't then you could either move it, or put the correct directory inside of Image.open().
I have the same issue.
This is because the test.py does not have the same pathname. If you are working in the same folder it will work.
However, the solution i found was to put in the full path + file name so that it is unambiguous.
"c:\...fullpath...\image.jpg"
You can do it like this:
from PIL import Image
import os
curDir = os.getcwd()
fileName = "image.jpg"
fn = curDir + "\\" + fileName
print(fn)
image = Image.open(fn)
image.show()
This works. Please let me know if you find better.