1

I got a Data set which full of images. My aim is converting this images to gray scale. I can easily do this with one image but I need to do whit multiple images. Here is my code;

import cv2
import glob

path = "/path/*.jpg"

for file in glob.glob(path):
    img = cv2.imread(file)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Gray image', gray)
    cv2.imwrite('/path/cat' + '_gray.jpg', gray)

When I run this script, it's only convert a single image but my aim is converting the all images in the path. I'm really beginer on image processing and OpenCv2 module. Thanks already now for your helps.

Levent Kaya
  • 31
  • 1
  • 3
  • [This](https://stackoverflow.com/questions/49070242/converting-images-to-csv-file-in-python/49070833#49070833) might help. Get a list of all your files first, then do your colour conversion (which you're doing correctly as far as I can tell). – Pam Mar 19 '20 at 16:31
  • greate! I think it will. – Levent Kaya Mar 19 '20 at 16:33

1 Answers1

2

'/path/cat' + '_gray.jpg' always gives you /path/cat_gray.jpg, regardless of the input filename.

You probably want to use some part of the original file name there, which you can find using the functions in the os.path module.

For example:

import cv2
import glob
import os.path

path = "/path/*.jpg"

for file in glob.glob(path):
    img = cv2.imread(file)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Gray image', gray)
    basename = os.path.basename(file)  # e.g. MyPhoto.jpg
    name = os.path.splitext(basename)[0]  # e.g. MyPhoto
    cv2.imwrite('/path/' + name + '_gray.jpg', gray)
Thomas
  • 174,939
  • 50
  • 355
  • 478