Python Forum

Full Version: Looping through each images in a give folder Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
Error:
new = alpha * imgs + beta ~~~~~~^~~~~~ TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'
Not able to find where I am going wrong:
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 magic
cv2 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.")

Output:
SystemExit: 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.