how to put the image from folder into cycle

I have this code. But i need to find xmin,xmax,ymin,ymax for all images from folder and after this put name of the image, parametres in list dict. I do not understand how to put this from folder to string (#read image)(i mean, img = cv2.imread('C:\Blobs\SR1.png', cv2.IMREAD_UNCHANGED) - it is O.K. but when img = cv2.imread('SR1.png', cv2.IMREAD_UNCHANGED) - error). And if it is possible, how to do this by cycle.

import os
FOLDER_PATH = r'C:\\Blobs'

def listDir(dir):
  fileNames = os.listdir(dir)
  for fileName in fileNames:
    print('File Name: ' + fileName)
    print('Folder Path: ' + os.path.abspath(os.path.join(dir,fileName)), 
sep='\n')
if __name__ == '__main__':
  listDir(FOLDER_PATH)##
import cv2

# read image
img = cv2.imread('C:\\Blobs\\SR1.png', cv2.IMREAD_UNCHANGED)

xmin = 0
ymin = 0
ymax = img.shape[0] - 1
xmax = img.shape[1] - 1

print('xmin       : ', xmin)
print('xmax       : ', xmax)
print('ymin       : ', ymin)
print('ymax       : ', ymax)

Upvotes: 0

Views: 215

Answers (1)

marcos
marcos

Reputation: 4510

Considering that xmin and ymin will always be 0 and xmax and ymax will be equal to the dimensions of the image - 1. You can use opencv package for it, you need to pip install it. Once you have it you can just do this:

import os
import cv2

def get_dimensions(img_path):
    # read image
    img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)

    xmin = 0
    ymin = 0 
    ymax = 
    xmax = img.shape[1] - 1

    return {
        'xmin': 0,
        'xmax': img.shape[0] - 1,
        'ymin': 0,
        'ymax': img.shape[0] - 1
    }

def list_files(dir_path):
    files_and_folders = [
      os.path.abspath(os.path.join(dir_path,file_or_folder)) for file_or_folder in os.listdir(dir_path)
    ]
    return [file for file in files_and_folders if os.path.isfile(file)]


def get_img_data(dir_path):
    return [
        {**get_dimensions(img_path), 'name':os.path.basename(img_path)} for img_path in list_files(dir_path)
    ]

This is an example, I use the function get_img_data with the path /tmp/, it will look for all files in that directory and read them (be sure the directory path you use contains only images), then in output I store the result, which I print, it will have the xmin, xmax, ymin, ymax values and the name of the file.

output = get_img_data('/tmp/')
print(output)
>>> '[{'xmin': 0, 'xmax': 199, 'ymin': 0, 'ymax': 199, 'name': 'a.png'}, {'xmin': 0, 'xmax': 199, 'ymin': 0, 'ymax': 199, 'name': 'b.png'}]'

Upvotes: 1

Related Questions