Errno 2 No such file or directory: 'Phone_1.jpg' - python

New to coding and don't understand the error I am getting. Included below is my code and the traceback:
import PIL
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path
import PIL.ImageDraw
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
def round_corners(original_image, percent_of_side):
""" Rounds the corner of a PIL.Image
original_image must be a PIL.Image
Returns a new PIL.Image with rounded corners, where
0 < percent_of_side < 1
is the corner radius as a portion of the shorter dimension of original_image
"""
font = ImageFont.truetype("arial.ttf", 15)
# Opening the file gg.png
imageFile = ("new.jpg")
im1=Image.open(imageFile)
# Drawing the text on the picture
draw = ImageDraw.Draw(im1)
draw.text((0,0), "SAMSUNG",(0,0,255),font=font)
im1.save("marked_image.png")
#set the radius of the rounded corners
width, height = original_image.size
radius = int(percent_of_side * min(width, height)) # radius in pixels
###
#create a mask
###
#start with transparent mask
rounded_mask = PIL.Image.new('RGBA', (width, height), (127,0,127,0))
drawing_layer = PIL.ImageDraw.Draw(rounded_mask)
# Overwrite the RGBA values with A=255.
# The 127 for RGB values was used merely for visualizing the mask
# Draw two rectangles to fill interior with opaqueness
drawing_layer.polygon([(radius,0),(width-radius,0),
(width-radius,height),(radius,height)],
fill=(127,0,127,255))
drawing_layer.polygon([(0,radius),(width,radius),
(width,height-radius),(0,height-radius)],
fill=(127,0,127,255))
#Draw four filled circles of opaqueness
drawing_layer.ellipse((0,0, 2*radius, 2*radius),
fill=(0,127,127,255)) #top left
drawing_layer.ellipse((width-2*radius, 0, width,2*radius),
fill=(0,127,127,255)) #top right
drawing_layer.ellipse((0,height-2*radius, 2*radius,height),
fill=(0,127,127,255)) #bottom left
drawing_layer.ellipse((width-2*radius, height-2*radius, width, height),
fill=(0,127,127,255)) #bottom right
# Uncomment the following line to show the mask
# plt.imshow(rounded_mask)
# Make the new image, starting with all transparent
result = PIL.Image.new('RGBA', original_image.size, (0,0,0,0))
result.paste(original_image, (0,0), mask=rounded_mask)
return result
def get_images(directory=None):
""" Returns PIL.Image objects for all the images in directory.
If directory is not specified, uses current directory.
Returns a 2-tuple containing
a list with a PIL.Image object for each image file in root_directory, and
a list with a string filename for each image file in root_directory
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
image_list = [] # Initialize aggregaotrs
file_list = []
directory_list = os.listdir(directory) # Get list of files
for entry in directory_list:
absolute_filename = os.path.join(directory, entry)
try:
image = PIL.Image.open(absolute_filename)
file_list += [entry]
image_list += [image]
except IOError:
pass # do nothing with errors tying to open non-images
return image_list, file_list
def round_corners_of_all_images(directory=None):
""" Saves a modfied version of each image in directory.
Uses current directory if no directory is specified.
Places images in subdirectory 'modified', creating it if it does not exist.
New image files are of type PNG and have transparent rounded corners.
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
# Create a new directory 'modified'
new_directory = os.path.join(directory, 'modified')
try:
os.mkdir(new_directory)
except OSError:
pass # if the directory already exists, proceed
#load all the images
image_list, file_list = get_images(directory)
#go through the images and save modified versions
for n in range(len(image_list)):
# Parse the filename
filename, filetype = file_list[n].split('.')
# Round the corners with radius = 30% of short side
new_image = round_corners(image_list[n],.30)
#save the altered image, suing PNG to retain transparency
new_image_filename = os.path.join(new_directory, filename + '.png')
new_image.save(new_image_filename)
There is the full code and here is the traceback:
IOError Traceback (most recent call last)
<ipython-input-19-8a0b83840aa4> in <module>()
----> 1 round_corners_of_all_images()
C:\Users\ewainscott2019\Desktop\Computer Science\Semester 2\Image Artist\Image Artist Code.py in round_corners_of_all_images(directory)
124
125 # Round the corners with radius = 30% of short side
--> 126 new_image = round_corners(image_list[n],.30)
127 #save the altered image, suing PNG to retain transparency
128 new_image_filename = os.path.join(new_directory, filename + '.png')
C:\Users\ewainscott2019\Desktop\Computer Science\Semester 2\Image Artist\Image Artist Code.py in round_corners(original_image, percent_of_side)
20 # Opening the file gg.png
21 imageFile = ("new.jpg")
---> 22 im1=Image.open(imageFile)
23
24 # Drawing the text on the picture
C:\Users\ewainscott2019\AppData\Local\Enthought\Canopy\User\lib\site-packages\PIL\Image.pyc in open(fp, mode)
2270 filename = str(fp.resolve())
2271 if filename:
-> 2272 fp = builtins.open(filename, "rb")
2273
2274 try:
IOError: [Errno 2] No such file or directory: 'Phone_1.jpg'
I don't understand my error I have in the code. I have tried receiving help elsewhere but cannot find out anything. This is a school project that is overdue and I need to get it done.

Related

Python Program Doesn't Recognize Input

I have a program that is supposed to convert an image to a squared png with transparent borders (if the image is 1000x1500 then the png is 1500x1500 and then the image will be placed on the middle of the png creating a transparent border of 250x1500 on both sides). The program is supposed to import the image from a folder which I you can choose which you wish to import from, and then export it to another folder that you can also choose. I use recursion to go throw all images from the folder, however it says that the input is not recognizable. Can anyone help me with this one? You have everything you need explained on the code I'll send right now:
from PIL import Image
from os import listdir
from os.path import isfile, join,splitext
Folder_Input = 'D:\\0Pi_\Downloads\ScpServer\Originais' #directory where we will upload images
Folder_Output ='D:\\0Pi_\Downloads\ScpServer\PNGs' #directory where we will save images
typelist = ['.png','.jpg','.jpeg']
images_list = [f for f in listdir(Folder_Input) if isfile(join(Folder_Input, f)) and splitext(f)[1].lower() in typelist]
for im in images_list:
try:
image = Image.open(im) #this is supposed to open the image, however it doesn't. what's missing
except:
print(f'Problem opening image{im}!\n')
image.close()
continue
width, height = image.size
if height >= width:
new_width = height
new_height = height
else:
new_width = width
new_height = width
result = Image.new(mode = 'RGBA', size = (new_width, new_height) ,color = (0,0,0,0)) #creates a new transparent squared png
offset = ((new_width - width) // 2, (new_height - height) // 2) #centers the image in relation to the squared png
result.paste(image,offset) #unites both the image and the squared layer
image.close() #closes the file now finished
output_file = join(Folder_Output,splitext(im)[0] + '.png')
if not isfile(output_file):
result.save(output_file) #saves file on the output folder
else:
print(f"The file {splitext(im)[0] + '.png'} was not saved because it already exists on {Folder_Output}!\n")
This is the Tracebak:
Traceback (most recent call last):
File "D:/0Pi_/Documents/add_borders.py", line 16, in <module>
image.close()
builtins.NameError: name 'image' is not defined
If the try/except block fails, it may not have assigned the object to the image variable.
try:
image = Image.open(im) # this is supposed to open the image, however it doesn't. what's missing
except:
print(f'Problem opening image{im}!\n')
image.close() # will have problem here
Since, you are looking only to the Image.open(im) if it was succeed, just remove image.close() from the except or, use another try/except to close the object. Maybe the im is not readable or have a wrong path, so that will cause to fail.

syntax error- cropping image using bounding box coordinates

I want to achieve coordinates using the last four numbers (which represent center and dimensions of bounding box) and crop the bounding box from the image with the same name (.jpg format).
I have written the following code:
import os
from PIL import Image
from os import listdir
directory = "/home/masoud/masoud/crop/obj"
for file in os.listdir(directory):
if file.endswith(".txt"):
with open(os.path.join(directory, file), 'r') as f:
for line in f: # changed to file handle
line = line.rstrip() # remove trailing '\n'
nums = line.split()
four_nums = nums[1:5]
# print(four_nums)
image_name = os.path.splitext(os.path.join(directory, file)[0]+'.jpg'
img = Image.open(os.path.join(directory, image_name))
width, height = img.size
# # Setting the points for cropped image
left = width * (nums[1]- nums[3]/2)
top = height * (nums[2]- nums[4]/2)
right = width * (nums[1]+ nums[3]/2)
bottom = height * (nums[2]+ nums[4]/2)
# # Cropped image of above dimension
# # (It will not change orginal image)
im_cropped = img.crop((left, top, right, bottom))
im_cropped.show()
im_cropped.save('/home/masoud/masoud/crop/cropped-images', 'JPEG')
else:
continue
and txt files contents looks like below:
0 0.3547 0.5096 0.7293 1.0258
but I am getting the following syntax error.
File "/home/masoud/masoud/crop/crop.py", line 18
img = Image.open(os.path.join(directory, image_name))
^
SyntaxError: invalid syntax
[Finished in 0.4s with exit code 1]
[cmd: ['/home/masoud/anaconda3/bin/python3', '-u', '/home/masoud/masoud/crop/crop.py']]
[dir: /home/masoud/masoud/crop]
[path: /home/masoud/bin:/home/masoud/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
also directories look like this:
directories
You should use some IDE having a syntax check, like PyCharm CE,
not the line 18, but line 17 is the problem:
You are missing the closing bracket ")"
image_name = os.path.splitext(os.path.join(directory, file)[0]+'.jpg'
i assume you want:
image_name = os.path.splitext(os.path.join(directory, file))[0]+'.jpg'

Why are my cropped images being saved to the incorrect directory?

I'm writing a program that iterates over a directory of satellite images, crops each image to have a square aspect ratio (1:1), and then saves the cropped image in a different directory created at the beginning of the program. I'm able to crop each image successfully, but the cropped image is being saved to its original directory instead of the one created at the start of the program.
For example, the file path leading up to, but not including, the directory containing imagery is C:\Users\nickm\Documents\Projects\Platform\Imagery, while the directory containing the satellite imagery is dir (a subdirectory of Imagery). After each image is cropped, I want to save it to the directory created at the start of the program (e.g. 10-22-18 cropped, which will also be a subdirectory of Imagery). Instead, it's being saved in dir, overwriting the original image.
Here's my code:
# image.py
import datetime
import os
from PIL import Image
def make_new_dir(abs_path):
'''Creates the directory where our cropped imagery will be saved and
returns its absolute file path.
'''
date_obj = datetime.datetime.now()
date = date_obj.strftime('%x').replace('/', '-')
new_path = abs_path + '/' + date + ' cropped'
os.mkdir(new_path)
return new_path
def get_crop_area(image):
'''Crops each image to have a square aspect ratio (1:1) using the
image's size.
'''
image_width, image_height = image.size
diff = max(image_width, image_height) - min(image_width, image_height)
if image_width > image_height:
return [diff / 2, 0, image_width - diff / 2, image_height]
else:
return [0, diff / 2, image_width, image_height - diff / 2]
def crop_images(abs_path, image_dir, new_dir):
'''Iterates over the directory containing the satellite images
(abs_path + image_dir), cropping each image and saving it to our
new directory (the value returned from our make_new_dir function).
'''
new_dir = os.path.abspath(new_dir)
image_dir = os.path.join(abs_path, image_dir)
images = os.listdir(image_dir)
for image in images:
image_path = os.path.join(image_dir, image)
image = Image.open(image_path)
crop_area = get_crop_area(image)
cropped_image = image.crop(crop_area)
cropped_image_path = os.path.join(new_dir, image.filename)
cropped_image.save(cropped_image_path, 'JPEG')
The program is being run with run.py. abs_path and image_dir are being provided by the user at the command line and used as arguments in our make_new_dir and crop_images functions. This is what it looks like when I start my script from the command line:
C:\Users\nickm\Documents\Projects\Code\image>python run.py C:\Users\nickm\Documents\Projects\Platform\Imagery dir
Note that the absolute file path and the directory containing the images are two different command line arguments.
Here's my run.py script:
# run.py
import sys
from image import make_new_dir, get_crop_area, crop_images
if __name__ == '__main__':
filename, abs_path, image_dir = sys.argv
new_dir = make_new_dir(abs_path)
crop_images(abs_path, image_dir, new_dir)
This is the first program I've created that isn't just a basic coding exercise, so I'm wondering if I'm incorrectly implementing os.path.join. I've looked here and here for clarification, but neither employs the os module, which I'm pretty sure is where I'm encountering my issue.
Thanks in advance for any help provided.
If image.filename returns the full image path, you can get only the filename by doing this:
image_filename = os.path.basename(image.filename)

Resize multiple images in a folder (Python)

I already saw the examples suggested but some of them don't work.
So, I have this code which seems to work fine for one image:
im = Image.open('C:\\Users\\User\\Desktop\\Images\\2.jpg') # image extension *.png,*.jpg
new_width = 1200
new_height = 750
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\resized.tif') # .jpg is deprecated and raise error....
How can I iterate it and resize more than one image ? Aspect ration need to be maintained.
Thank you
# Resize all images in a directory to half the size.
#
# Save on a new file with the same name but with "small_" prefix
# on high quality jpeg format.
#
# If the script is in /images/ and the files are in /images/2012-1-1-pics
# call with: python resize.py 2012-1-1-pics
import Image
import os
import sys
directory = sys.argv[1]
for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))
x,y = image.size
new_dimensions = (x/2, y/2) #dimension set here
output = image.resize(new_dimensions, Image.ANTIALIAS)
output_file_name = os.path.join(directory, "small_" + file_name)
output.save(output_file_name, "JPEG", quality = 95)
print("All done")
Where it says
new_dimensions = (x/2, y/2)
You can set any dimension value you want
for example, if you want 300x300, then change the code like the code line below
new_dimensions = (300, 300)
I assume that you want to iterate over images in a specific folder.
You can do this:
import os
from datetime import datetime
for image_file_name in os.listdir('C:\\Users\\User\\Desktop\\Images\\'):
if image_file_name.endswith(".tif"):
now = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
im = Image.open('C:\\Users\\User\\Desktop\\Images\\'+image_file_name)
new_width = 1282
new_height = 797
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\test_resize\\resized' + now + '.tif')
datetime.now() is just added to make the image names unique. It is just a hack that came to my mind first. You can do something else. This is needed in order not to override each other.
I assume that you have a list of images in some folder and you to resize all of them
from PIL import Image
import os
source_folder = 'path/to/where/your/images/are/located/'
destination_folder = 'path/to/where/you/want/to/save/your/images/after/resizing/'
directory = os.listdir(source_folder)
for item in directory:
img = Image.open(source_folder + item)
imgResize = img.resize((new_image_width, new_image_height), Image.ANTIALIAS)
imgResize.save(destination_folder + item[:-4] +'.tif', quality = 90)

How do I fix my error with PIL and numpy images

You have to run it in the folder with a couple images and run shuffle_all_images() and it will create new folder and randomly generate all of the values for each pixel. I think it has to do with not converting to numpy images as opposed to PIL images?, but I can't figure it out.
import random
import os.path
import PIL
import numpy
def image_shuffle(original_image):
for row in len(original_image):
for col in len(original_image[1]):
r,g,b = original_image[row][col]
r = random.randint(1,255)
g = random.randint(1,255)
b = random.randint(1,255)
original_image[row][col] = [r, g, b]
return original_image
def get_images(directory=None):
""" Returns PIL.Image objects for all the images in directory.
If directory is not specified, uses current directory.
Returns a 2-tuple containing
a list with a PIL.Image object for each image file in root_directory, and
a list with a string filename for each image file in root_directory
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
image_list = [] # Initialize aggregaotrs
file_list = []
directory_list = os.listdir(directory) # Get list of files
for entry in directory_list:
absolute_filename = os.path.join(directory, entry)
try:
image = PIL.Image.open(absolute_filename)
file_list += [entry]
image_list += [image]
except IOError:
pass # do nothing with errors tying to open non-images
return image_list, file_list
def shuffle_all_images(directory=None):
""" Saves a modfied version of each image in directory.
Uses current directory if no directory is specified.
Places images in subdirectory 'modified', creating it if it does not exist.
New image files are of type PNG and have transparent rounded corners.
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
# Create a new directory 'modified'
new_directory = os.path.join(directory, 'modified')
try:
os.mkdir(new_directory)
except OSError:
pass # if the directory already exists, proceed
#load all the images
image_list, file_list = get_images(directory)
#go through the images and save modified versions
for n in range(len(image_list)):
# Parse the filename
filename, filetype = file_list[n].split('.')
# Round the corners with radius = 30% of short side
new_image = image_shuffle(image_list[n])
#save the altered image, suing PNG to retain transparency
new_image_filename = os.path.join(new_directory, filename + '.png')
new_image.save(new_image_filename)
The image_shuffle function is wrong.
It should be:
for row in range(original_image.size[0]):
for col in range(original_image.size[1]):
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
original_image.putpixel((row, col), (r,g,b))
You want to have color values starting from 0 unless you don't want to get all the possible colors.

Categories

Resources