In Python, how we can convert a .jpg file to a text file with triple comma-separated values of RGB, where these triples are separated by one space. For example:
0,0,200 0,0,10 10,0,0
90,90,50 90,90,10 255,255,255
100,100,88 80,80,80 15,75,255
The above is an image represented by 3x3 pixels. For each pixel the Blue, Green and Red values are provided, separated by commas. The top left pixel has (Blue=0,Green=0,Red=200). The top-right pixel has (Blue=10,Green=0,Red=0). The bottom-right pixel has (Blue=15,Green=75,Red=255). The bottom-left pixel has (Blue=100,Green=100, Red=88).
I could print out each pixel in a new line using the following code:
import cv2
img = imread('myimage.png')
for i in img:
for j in i:
print(*j,sep=',')
Can anyone help me?
CodePudding user response:
print()
has an arg to change default ending from \n
. And then you can print a newline at the end of every row of pixels.
import cv2
img = cv2.imread('myimage.png')
for i in img:
for j in i:
print(*j, sep=',', end=' ')
print()
CodePudding user response:
These lines of code solved my problem, thanks to user3474165:
import cv2
from pathlib import Path
path = Path('.').joinpath('images') # you shoud adjust this address upon your need
img = cv2.imread(path.joinpath('image_name')) # you should change 'image_name' upon your need
with open(path.joinpath('output.txt'), 'w') as f_out: # you should change 'output.txt' upon your need
for i in img:
f_out.write(' '.join(['{},{},{}'.format(*j) for j in i]) '\n')