使用python和opencv将文件夹中的图像转换为灰度并将其写入特定的文件夹 [英] Converting images in a folder to grayscale using python and opencv and writing it to a specific folder

查看:363
本文介绍了使用python和opencv将文件夹中的图像转换为灰度并将其写入特定的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

#多次图像转换

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 = [f for f in listdir(path) if isfile(join(path,f))] 
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(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
        cv2.imwrite(os.path.join(dstpath,fil),gray_image)
    except:
        print('{} is not converted')

这篇关于使用python和opencv将文件夹中的图像转换为灰度并将其写入特定的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆