Reputation: 55
i've an issue with 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
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. but why my cv2.imwrite
code not saving the grayscale image to folder? i've searched answer in this forum but none of them answer my question. any answer would be appreciated. thanks in advance !
Upvotes: 4
Views: 12294
Reputation: 23556
Please, don't do this, especially chdir()
etc.:
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)
Upvotes: 3
Reputation: 189
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.
Upvotes: 0