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()
Related
This is my code. It works well and able to write the image to the specified folder in IDE. But, after converting the .py file to .exe file by PyInstaller, cv2.imwrite does not work anymore. Is there anyone can help me to solve this issue?
# enter code here
import cv2
import os
# Image path
image_path = r'C:\Users\Meadow\Desktop\Saving Images\jeremy.jpg'
# Image directory
directory = r'C:\Users\Meadow\Desktop\Saving Images'
# Using cv2.imread() method to read the image
img = cv2.imread(image_path)
# Change the current directory to specified directory
os.chdir(directory)
# List files and directories in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before saving image:")
print(os.listdir(directory))
# Filename
filename = 'savedImage.jpg'
# Using cv2.imwrite() method
# Saving the image
cv2.imwrite(filename, img)
# List files and directories
# in 'C:/Users / Rajnish / Desktop / GeeksforGeeks'
print("After saving image:")
print(os.listdir(directory))
print('Successfully saved')
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 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'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.
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.