Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting images in a folder to grayscale using python and opencv and writing it to a specific folder

import glob
import cv2
import os
import numpy as np
from PIL import Image
images=[]
images=np.array(images)
path='C:\Users\Quantum\Desktop\test'
count=0
images = [cv2.imread(file,0) for file in glob.glob("E:\homework\Computer vision\Faces\*.jpg")]
for i in range(len(images)):
#    im = Image.fromarray(images[i])
#    cv2.imwrite(str(path) + '.jpg', images[count])
    cv2.imwrite(os.path.join(path, 'pic.jpg'), images[count])
    count+=1

Trying to select all the images from a folder and the images are getting selected and are converted to grayscale although I dont know how to write those images to a specific folder.Kindly help

like image 986
prateek parab Avatar asked Dec 03 '25 18:12

prateek parab


1 Answers

#multiple image conversions

import cv2

import os,glob

from os import listdir,makedirs

from os.path import isfile,join
path = '/root/Desktop/Anil' # Source Folder
dstpath = '/root/Desktop/Anil2' # Destination Folder
try:
    makedirs(dstpath)
except:
    print ("Directory already exist, images will be written in same folder")
# Folder won't used
files = list(filter(lambda f: isfile(join(path,f)), listdir(path)))
for image in files:
    try:
        img = cv2.imread(os.path.join(path,image))
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        dstPath = join(dstpath,image)
        cv2.imwrite(dstPath,gray)
    except:
        print ("{} is not converted".format(image))
for fil in glob.glob("*.jpg"):
    try:
        image = cv2.imread(fil) 
        gray_image = cv2.cvtColor(os.path.join(path,image), cv2.COLOR_BGR2GRAY) # convert to greyscale
        cv2.imwrite(os.path.join(dstpath,fil),gray_image)
    except:
        print('{} is not converted')
        
like image 111
Anil Sah Avatar answered Dec 06 '25 06:12

Anil Sah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!