I'm starting with Python in Machine Learning, I'm interested in solving old Kaggle competition for my own. First thing I need to do is to convert list of encoded pixels to a bounding box, convert it to have top left and bottom right rectangle coordinates, have it in specific output and save it to a file
I found already examples where using RLE algorithm convert encoded pixels and I need to change it to save to the file. My particular problem is saving a tuple to a file in x1,y1,x2,y2
format
I have a code, which takes the first and the last coordinate from the list of pixels. First I tried with:
f = open("file.txt", "w")
f.write(str(mask_pixels[0]) + str(mask_pixels[len(mask_pixels)-1]))
f.write("\n")
f.close()
But the output is like (469, 344)(498, 447)
(which is a tuple, so that's fine).
I tried to use join
function as following:
coordinates = mask_pixels[0], mask_pixels[len(mask_pixels)-1]
f = open("file.txt", "w")
for x in coordinates:
f.write(",".join(str(x)))
f.write("\n")
f.close()
But it saves it as (,4,6,9,,, ,3,4,4,)(,4,9,8,,, ,4,4,7,)
So I tried with
f = open("file.txt", "a")
f.write(str(coordinate1))
f.write(",")
f.write(str(coordinate2))
f.write("\n")
f.close()
But it saves it as (469, 344),(498, 447)
, which is still something I'm not looking for. Can anyone show me a hint how should I do it to have in a file something like 469,344,498,447
? I'm not asking for a code directly (I know you guys might not have time for it), but I'm looking for an idea what should I read/learn.
with open("file.txt", "w") as f:
print(*sum((mask_pixels[0],mask_pixels[-1]),()),sep=', ',file=f)
Output
469, 344, 498, 447
You can transform your tuples in list and concatenate them :
a = (469, 344)
b= (498,447)
result = list(a) + list(b)
Output :
[469, 344, 498, 447]
To go back to your code it could look something like that :
f = open("file.txt", "w")
f.write(str(list(str(mask_pixels[0])) + list(str(mask_pixels[len(mask_pixels)-1]))))
f.write("\n")
f.close()
And if you want to save all of your mask you could even do a double list comprehension :
a = (469, 344)
b= (498,447)
c = (512,495)
list_of_tuples = [a, b, c]
result = [item for sublist in list_of_tuples for item in sublist]
Out : [469, 344, 498, 447, 512, 495]
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.