Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

python - Opening files from directory in specific order

I have a folder that contains around 500 images that I am rotating at a random angle from 0 to 360. The files are named 00i.jpeg where i = 0 then i = 1. For example I have an image named 009.jpeg and one named 0052.jpeg and another one 00333.jpeg. My code below works as is does rotate the image, but how the files are being read through is not stepping correctly.

I would think I would need some sort of stepping code chunk that starts at 0 and adds one each time, but I'm not sure where I would put that. os.listdir doesn't allow me to do that because (from my understanding) it just lists the files out. I tried using os.walk but I cannot use cv2.imread. I receive a SystemError: <built-in function imread> returned NULL without setting an error error.

Any suggestions?

import cv2
import imutils
from random import randrange
import os

os.chdir("C:\Users\name\Desktop\training\JPEG")


j = 0
for infile in os.listdir("C:\Users\name\Desktop\training\JPEG"):
    filename = 'testing' + str(j) + '.jpeg'
    i = randrange(360)
    image = cv2.imread(infile)
    rotation_output = imutils.rotate_bound(image, angle=i)
    os.chdir("C:\Users\name\Desktop\rotate_test")
    cv2.imwrite("C:\Users\name\Desktop\rotate_test\" + filename, rotation_output)
    os.chdir("C:\Users\name\Desktop\training\JPEG")
    j = j + 1
print(infile)
000.jpeg
001.jpeg
0010.jpeg
00100.jpeg
...

Needs to be:

print(infile)
000.jpeg
001.jpeg
002.jpeg
003.jpeg
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Get a list of files first, then use sort with key where the key is an integer version of the file name without extension.

files = os.listdir("C:\Users\name\Desktop\training\JPEG")
files.sort(key=lambda x:int(x.split('.')[0]))

for infile in files:
    ...

Practical example:

files = ['003.jpeg','000.jpeg','001.jpeg','0010.jpeg','00100.jpeg','002.jpeg']
files.sort(key=lambda x:int(x.split('.')[0]))
print(files)

Output

['000.jpeg', '001.jpeg', '002.jpeg', '003.jpeg', '0010.jpeg', '00100.jpeg']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...