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.

2
  • This 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). Commented Mar 19, 2020 at 16:31
  • greate! I think it will. Commented Mar 19, 2020 at 16:33

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.