Reputation: 11
Hi i've a script to run image process on a image. But i'm trying to get a loop or another way to read multiple images from a file
e.g
C:\Users\student\Desktop\Don\program (opencv version)\Images\move1
move1 contains images named as frame1.jpg , frame2.jpg , frame3.jpg...
The script i'm using to run the image process is something like
img = cv2.imread('frame1.jpg')
mimg = cv2.medianBlur(img,15)
gimg = cv2.cvtColor(mimg,cv2.COLOR_RGB2GRAY)
ret,th1 = cv2.threshold(gimg, 160,255,cv2.THRESH_BINARY)
ret,th2 = cv2.threshold(th1, 160,255,cv2.THRESH_BINARY_INV)
cv2.imwrite('threshbinaryinv.jpg', th2)
My script above could only read images that i manually keyed in e.g 'frame1.jg'. Sorry i'm very new to python. Thanks!
EDIT This the code i edited with you guys help.. still getting error as "Traceback (most recent call last): File "C:\Users\student\Desktop\Don\program (opencv version)\prog.py", line 32, in gimg = cv2.cvtColor(mimg,cv2.COLOR_RGB2GRAY) #convert RBG to Grayscale cv2.error: D:\Build\OpenCV\opencv-3.3.1\modules\imgproc\src\color.cpp:11048: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor"
CODE
path_of_images = 'C:/Users/student/Desktop/Don/program (opencv version)/Images'
list_of_images = os.listdir(path_of_images)
for image in list_of_images:
img = cv2.imread(os.path.join(path_of_images, image))
mimg = cv2.medianBlur(img,15)
gimg = cv2.cvtColor(mimg,cv2.COLOR_RGB2GRAY)
ret,th1 = cv2.threshold(gimg, 160,255,cv2.THRESH_BINARY)
ret,th2 = cv2.threshold(th1, 160,255,cv2.THRESH_BINARY_INV)
cv2.imwrite('threshbinaryinv.jpg', th2)
Upvotes: 0
Views: 3207
Reputation: 7399
You can use os.listdir() to get the names of all images in your specified path which is "C:\Users\student\Desktop\Don\program (opencv version)\Images". Then you can loop over the names of images like :
import os
import cv2
path_of_images = r"C:\Users\student\Desktop\Don\program (opencv version)\Images"
list_of_images = os.listdir(path_of_images)
for image in list_of_images:
img = cv2.imread(os.path.join(path_of_images, image))
"""Your code here"""
Upvotes: 1
Reputation: 22954
It can be done using a for
loop and generating a new str
file name and then processing it as:
IMG_FOLDER_PREFIX = "absolute/path/to/frame"
IMG_EXTENSION = ".jpg"
NUM_IMAGES = 10
for i in xrange(NUM_IMAGES):
image_path = IMG_FOLDER_PREFIX + str(i) + IMG_EXTENSION
img = cv2.imread(image_path)
# Other Image Processing.
A better way to iterate images would be os.listdir
, glob
, etc. but in that case you may have lesser control over the order of files traversed.
Upvotes: 0