![]() |
Looping through each images in a give folder Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Looping through each images in a give folder Python (/thread-43808.html) |
Looping through each images in a give folder Python - druva - Jan-01-2025 Here I am trying to loop through each image file in a folder . The code : import cv2 import numpy as np import os # Directory containing jpg files directory = r"F:/PyProject/PyCode/Images" imgs=[] # Loop through each file in the directory for filename in os.listdir(directory): imgs = cv2.imread(filename) alpha = 2.0 beta = -130 new = alpha * imgs + beta new = np.clip(new, 0, 255).astype(np.uint8) # file name should be 01_filename.jpg cv2.imwrite("index_filename.'jpg'", new) Not able to find where I am going wrong:
RE: Looping through each images in a give folder Python - Pedroski55 - Jan-01-2025 What exactly do you want to do? You declared imgs as an empty list: Quote:imgs=[] Then later: for filename in os.listdir(directory): imgs = cv2.imread(filename)That is a problem. But if filename exists, you should be able to read it. The problem is, you have no path, just the names of the files in your path if you use os.listdir(directory)you get a list of file names in that directory, but not the path to the file. The simplest solution is: # Directory containing jpg files directory = r"F:/PyProject/PyCode/Images/" for filename in os.listdir(directory): img = cv2.imread(directory + filename) # do some magiccv2 will not raise an error if you give it a non-existent image name to read. I have no image called bigpic.jpg in my path destination. Try something like this import cv2 as cv import sys destination = 'cv2/images/steps/' name = input('Enter the name of the picture you want to analyse ... ') # Enter the name of the picture you want to analyse ... bigpic.jpg image = cv.imread(destination + name, cv.IMREAD_GRAYSCALE) if image is None: sys.exit("Could not read the image.") Look up the module pathlib and use Path to define the paths to your files, that will be much better than os.
|