简体   繁体   中英

.ppm file separate every 3 pixels

I have this code, that should ultimately mirror the ppm image. but I'm facing a problem is trying to separate every 3 pixels into its own brackets in a lists of lists.

for example I have this .ppm file:

P3 
44 
15
000 000  000 15015 
000 0157 000 000 
000 000  0157 000 
15015 000 000 000

I want to separate into lists of lists with every 3 pixels in brackets like this Ignoring the header:

[[('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0'), ('15', '0', '15')], [('0', '0', '0'), ('0', '15', '7'), ('0', '0', '0'), ('0', '0', '0')], [('0', '0', '0'), ('0', '0', '0'), ('0', '15', '7'), ('0', '0', '0')], [('15', '0', '15'), ('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0')]]

so far I've only been able to achieve this:

[['0', '0', '0', '0', '0', '0', '0', '0', '0', '15', '0', '15'], ['0', '0', '0', '0', '15', '7', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '0', '0', '15', '7', '0', '0', '0'], ['15', '0', '15', '0', '0', '0', '0', '0', '0', '0', '0', '0']]

how can I separate each three integers in the list of lists?

code:

takePPM = input("Enter the pmm file name: ")
openFile = open(takePPM, "r")
readFile = openFile.readlines()
lists = []
for row in readFile[3:]:
    lists.append(row.split())

print(lists)

Since you have the data you want placed nicely into lists , the following should work:

#convert each list in lists to lists of 3-tuples
target = []
for list in lists:
    target.append([tuple(list[i:i+3]) for i in range(0,len(list),3)])

print(target) #target list with lists of 3-tuples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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