简体   繁体   中英

How to convert multiple RGB images in one folder to grayscale in python

Someone could help me please, I want to convert my RGB images in one folder to grayscale at one time. I've been looking for some Python codes but haven't found any. I tried to do as following but it didn't work.

Here is my code:

from skimage.color import rgb2gray
from skimage.io import imread, imsave
from skimage.filters import threshold_otsu
from skimage import img_as_uint

inp_image = imread("C:/RGB/*.JPG")
img_gray = rgb2gray(inp_image)

thresh = threshold_otsu(img_gray)
binary_thresh_img = img_gray & gt; thresh

imsave("C:/Grayscale", img_as_uint(binary_thresh_img))

And it gave me following error:

OSError: [Errno 22] Invalid argument: 'C:/RGB/*.JPG'

You can get the list with the filenames with glob() .

import glob
for filename in glob.glob("C:/RGB/*.JPG"):
    inp_image = imread(filename)
    [...]

To add to the list of solutions:

import os
from PIL import Image

ORIGIN_PATH = "./folder1/"
DESTIN_PATH = "./folder2/"

for filename in os.listdir(ORIGIN_PATH):                                                                                                                                                                
    img = Image.open(ORIGIN_PATH + filename).convert("LA")                                                                                                                                                
    img.save(DESTIN_PATH + filename) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM