简体   繁体   English

用python制作一个黑白文件夹

[英]Making a folder black and white with python

I have a folder of JPEGs. 我有一个JPEG文件夹。 They are all RGB. 它们都是RGB。 I want to convert them all to greyscale with scikit-image. 我想使用scikit-image将它们全部转换为灰度。

import glob
from skimage.color import rgb2gray
from skimage.io import imread, imsave
from skimage.filters import threshold_otsu
from skimage import img_as_uint
import os
from PIL import Image


list = os.chdir("C:/Users/Images/RGB")
for file in list:
    image1 = Image.open(file)
    image_converted = color.rgb2gray(image1)
    io.imsave("C:/Users/Images/Greyscale", image_converted)

I get the error message : 我收到错误消息:

    AttributeError: 'JpegImageFile' object has no attribute 'ndim'

What am I doing wrongly here ? 我在这里做错了什么?

Give this code a try: 试试下面的代码:

from skimage import io, color
import os
import imghdr

source = r'C:\Users\Images\RGB'
destination = r'C:\Users\Images\Greyscale'

image_files = [os.path.join(root, filename) 
                   for root, dirs, files in os.walk(source) 
                   for filename in files 
                   if imghdr.what(os.path.join(root, filename))]

for fn in image_files:
    rgb = io.imread(fn)
    grey = color.rgb2gray(rgb)
    head, tail = os.path.split(fn)
    io.imsave(os.path.join(destination, tail), grey)

Notice that image_files is a list containing the full path name of all the image files found in source and its subdirectories (recursively). 请注意, image_files是一个列表,其中包含在source及其子目录(递归)中找到的所有图像文件的完整路径名。 The complete list of image types being detected can be found at the documentation of the imghdr module. 可在imghdr模块的文档中找到要检测的图像类型的完整列表。

It looks like you are not running the script in the directory the files are located. 看起来您没有在文件所在目录中运行脚本。

Either use the full file path for Image.open(file) or os.chdir into "C:/Users/Images/RGB" . 使用Image.open(file)os.chdir的完整文件路径进入"C:/Users/Images/RGB"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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