简体   繁体   English

cv2.imwrite 不保存图像

[英]cv2.imwrite not saving image

i've an issue with cv2.imiwrite我对cv2.imiwrite有疑问

there are two folders, the photos is for normal image then the gray is folder to save the grayscale image from normal photo that already changed有两个文件夹, photos是普通图像, gray是文件夹,用于保存已经更改的普通照片的灰度图像

i want to read a normal image and change to grayscale, and then save the grayscale我想读取正常图像并更改为灰度,然后保存灰度

so this is my code所以这是我的代码

import cv2
import os 
import glob

count = 0

os.chdir('./photos')
for file in glob.glob('*.jpg'):
    image = cv2.imread(file)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('./gray/grayscale{}.jpg'.format(count), image_gray)
    count += 1

the image = cv2.imread(file) have an array, and so the image_gray = cv2.cvtColor(image, cv2.COLORBGR2GRAY) have and array too. image = cv2.imread(file)有一个数组,所以image_gray = cv2.cvtColor(image, cv2.COLORBGR2GRAY)也有一个数组。 but why my cv2.imwrite code not saving the grayscale image to folder?但为什么我的cv2.imwrite代码没有将灰度图像保存到文件夹? i've searched answer in this forum but none of them answer my question.我已经在这个论坛中搜索了答案,但没有一个人回答我的问题。 any answer would be appreciated.任何答案将不胜感激。 thanks in advance !提前致谢 !

Please, don't do this, especially chdir() etc.:请不要这样做,尤其是chdir()等:

os.chdir('./photos')
for file in glob.glob('*.jpg'):
    image = cv2.imread(file)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('./gray/grayscale{}.jpg'.format(count), image_gray)
    count += 1

Instead you may use much easier:相反,您可以更轻松地使用:

if not os.path.isdir( 'gray' ) :
    os.mkdir( 'gray' )  # make sure the directory exists

for i, file in enumerate(glob.glob('photos/*.jpg')):
    image = cv2.imread(file)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('./gray/grayscale_%03d.jpg' % i, image_gray)

You should check that whether you're on designed directory您应该检查您是否在设计目录上

# Check current working directory.
retval = os.getcwd()
print "Current working directory %s" % retval

Make sure that 'gray' filder is existed or not.确保“灰色”文件夹是否存在。 I think there's no problem with your code.我认为你的代码没有问题。

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

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