Python cannot find a directory - python

I wrote a code like this with jupyter notebook in a project;
import os
image_path = r'C:\Users\ays\Desktop\IR\01.jpg'
image_files = os.listdir(image_path)
img = cv2.imread(os.path.join(image_path,image_files))
cv2.imshow('image',img)
it gives an error like;
[WinError 3] The system cannot find the path specified: 'C:\Users\ays\Desktop\IR\01.jpg'
i was trying to print an image and
i had a directory problem

The argument to os.listdir() must be the directory, not the image file, so remove \01.jpg.
Then you'll need to loop over the result of os.listdir(), since it returns a list.
import os
image_path = r'C:\Users\ays\Desktop\IR'
image_files = os.listdir(image_path)
for file in image_files:
img = cv2.imread(os.path.join(image_path,file))
cv2.imshow('image',img)

Your image_path seems to be a file, not a directory. Drop the file name and you should be OK:
image_path = r'C:\Users\ays\Desktop\IR'

Related

Can't find path to put images in a list?

I'm having some trouble getting my path to work when opening a folder. I put the folder of images into the same folder as the .py file that I'm coding in. Then I try to open it with this code:
images = []
for file in glob('./images/*.PNG'):
print(file)
im = Image.open(file)
images.append(im)
This, however, isn't working. I typed out the "print(file)" so I could see if it was even opening the file and it doesn't seem to even be doing that. I think it's a pathing issue but I have no idea because (as far as I'm concerned) that's the correct path. To reiterate, this "images" directory is in the same directory as the .py file I'm writing in. Any help would be greatly appreciated.
this is usually what I did when I need to access a file inside path:
import os
pathCurrent = os.getcwd() + '\\'
imageFile = pathCurrent + '*.PNG'
And then you can use it as:
images = []
for file in glob(imageFile):
print(file)
im = Image.open(file)
images.append(im)
Let me know if this help.
Maybe:
images = []
def is_img(p: Path) -> bool:
return p.suffix.upper() in ('.PNG', '.JPG', '.JPEG', '.ICO', '.BMP')
for file in glob('./images/*'):
if not is_img(file):
print(file.suffix)
continue
print(file)
im = Image.open(file)
images.append(im)

How to open a random image from specified folder/directory in Python OpenCV

I want my program to open a random image from the folder.
This works:
import cv2
import os
import random
capture = cv2.imread(".Images/IMG_3225.JPEG")
But when I want to do this random it doesn't work:
file = random.choice(os.listdir("./images/"))
capture = cv2.imread(file)
I'm getting the following error:
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
What am I doing wrong??
This happens because os.listdir returns the contents of a folder.
Having this folder structure:
images/
- a.png
- b.png
- c.png
This would be the expected result.
>>> os.listdir('images')
['a.png', 'b.png', 'c.png']
file actually contains the name of a file in images/, so cv2.imread does not find the file because it's looking for it in the wrong place.
You have to pass cv2.imread the path to the file:
IMAGE_FOLDER = './images'
filename = random.choice(os.listdir(IMAGE_FOLDER))
path = '%s/%s' % (IMAGE_FOLDER , filename)
capture = cv2.imread(path)
This is one of the small mistakes that we usually overlook while working on it. It is mainly because os.listdir returns the contents of a folder. When you are using os.listdir, it just returns file name. As a result it is running like capture = cv2.imread("file_name.png") whereas it should be capture = cv2.imread("path/file_name.png")
So when you are working, try to use the code snippet:
path = './images'
file = random.choice(os.listdir("./images/"))
capture = cv2.imread(os.path.join(path,file))
This will help you run the code.
Try this:
import os
import cv2
import random
dirs = []
for i in os.listdir("images"):
if i.endswith(".JPEG"):
dirs.append(os.path.join("images", i))
pic = random.choice(dirs)
pic_name = pic.split("\\")[-1]
pic = cv2.imread(pic)
cv2.imshow(pic_name, pic)
cv2.waitKey(0)

How can I change all the images in a folder and save the changed images to another folder?

I have a lot of images in a folder. I need to process each image the same way and save the processed images to a different folder. I imagine it something like this:
for i in range(nuber_of_file):
current_image = cv2.imread("path to file")
# transformation
cv2.imwrite("new path", new_image)
I am having difficulty getting the number of files in a folder and getting a new path each time. Can you please tell me how to do this?
You can use:
glob: to get all the files in your directory
rglob: (recursive glob) to get all the files in your directory and all sub directories
Then you can read them with cv2.imread.
here is an example:
from pathlib import Path
import cv2
def main():
destination_path = '/path/to/destination'
target_path = '/path/to/target'
format_of_your_images = 'jpg'
all_the_files = Path(destination_path).rglob(f'*.{format_of_your_images}')
for f in all_the_files:
p = cv2.imread(str(f))
# transformation
cv2.imwrite(f'{target_path}/{f.name}', p)
if __name__ == '__main__':
main()
Hope it was helpful
you can list the files in a folder with os.listdir(dirString). I gives you a list of files names, you can filter them like this :
dl = os.listdir(dirString)
imgList = list()
imgList.append([f for f in dl if ".JPEG" in f or ".jpg" in f or ".png" in f])
Then you get the full path and read the image like this:
img = cv2.imread(os.path.join(dirString, imgList[0]), cv2.IMREAD_COLOR)
Mathieu.

OS Error:[WinError 123] The filename, directory name, or volume label syntax is incorrect

I am trying to save images after converting them into grayscale from one folder to another. when I run my code, it keeps saving the file in the same folder and making duplicates of all the images. Here is my code, Please guide where my problem lies...
import glob
import cv2
import os
spath=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png"
dpath=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images\*.png"
files = os.listdir(spath)
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
print(filename)
img=cv2.imread(filename)
rl=cv2.resize(img, (40,50))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(dpath,filename), gray_image)
If you pass a full pathname to glob.glob(), then it will return the full path of the result files, not just the filenames.
That means in this loop in your code:
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
filename is a full path such as C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\myfile1.png.
Then, later in the loop when you call cv2.imwrite(os.path.join(dpath,filename), gray_image), you're trying to join together C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images\*.png and C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\myfile1.png, which is the cause of your error.
glob() is convenient to get the full path of just the files you want, but then you have to separate the filename from the directory.
Try using listdir() instead of glob():
import glob
import cv2
import os
sdir=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza"
ddir=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images"
for filename in os.listdir(sdir):
if not filename.lower().endswith(".png"):
continue
print(filename)
img=cv2.imread(os.path.join(sdir, filename))
rl=cv2.resize(img, (40,50))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(ddir,filename), gray_image)

How to move images to a different directory using Linux Ubuntu terminal

I am now trying to build a script that opens, rotates, resizes and saves several images contained in the images directory (running the pwd command gives the message /home/student-01-052f372bc989/images). The images contained in the images directory are of the format TIFF, have a resolution of 192x192 pixel and are rotated 90° anti-clockwise. The script must turn these images in the following formats:
.jpeg format
Image resolution 128x128 pixels
Should be straight
and save the modified images in the /opt/icons directory
Here is the code I currently have:
import os
from PIL import Image
Image_dir = '/home/student-01-052f372bc989/images'
imagedir = os.chdir(Image_dir)
new_dir = '/opt/icons'
for pic in os.listdir(os.getcwd()):
if pic.endswith(".tiff"):
img = Image.open(pic)
new_img = img.resize((128,128)).rotate(270)
newName = pic.replace(".tiff", ".jpeg")
newdir = os.chdir(new_dir)
new_img.save(newName, "JPEG")
imagedir = os.chdir(Image_dir)
The code has no issue when I run it, but when I run the ls /opt/icons command to check if the modified images were copied to the directory, the images are not yet there.
The script is currently located in the /home/student-01-052f372bc989/images directory.
Could someone please tell me what I did wrong?
So... with a bit of digging, i did manage to find an easier way to do the script
the code is as follows:
import os
from PIL import Image
old_path = os.path.expanduser('~') + '/images/'
new_path = '/opt/icons/'
for image in os.listdir(old_path):
if '.' not in image[0]:
img = Image.open(old_path + image)
img.rotate(-90).resize((128, 128)).convert("RGB").save(new_path + image.split('.')[0], 'jpeg')
img.close()

Categories