python - 使用python和opencv将文件夹中的图像转换为灰度并将其写入特定的文件夹

标签 python opencv grayscale

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

尝试从文件夹中选择所有图像,并且图像被选择并转换为灰度,尽管我不知道如何将这些图像写入特定的文件夹。

最佳答案

#多次图像转换

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')
        

关于python - 使用python和opencv将文件夹中的图像转换为灰度并将其写入特定的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087528/

相关文章:

python - 将第 N 维中的项目拆分并交换到第 N+1 维

python - 用排序索引替换 Pandas 列

opencv - 如何使用python单独获取黑色固体而忽略白色岛屿

python - 有没有一种简单的方法可以将纹理映射到 python 中的不同 "UV"系统?

ImageMagick将色彩空间减少为灰色

python - h5py 安装错误失败,退出状态为 2

python - Python 中的多行匹配

c++ - 如何将 Logo 作为水印添加到图像中?

android - 在Android中使用NDK(C/C++)对图像应用灰度效果

c++ - OpenCV 表单应用-Mat转Grayscale