简体   繁体   English

将图像转换为三逗号分隔 RGB 的 txt 文件

[英]convert an image to a txt file in triple comma separated RGB

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.在 Python 中,我们如何将 .jpg 文件转换为具有 RGB 三个逗号分隔值的文本文件,其中这些三元组由一个空格分隔。 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.上面是一个由 3x3 像素表示的图像。 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).左上角的像素有 (Blue=0,Green=0,Red=200)。 The top-right pixel has (Blue=10,Green=0,Red=0).右上角的像素有 (Blue=10,Green=0,Red=0)。 The bottom-right pixel has (Blue=15,Green=75,Red=255).右下角的像素有 (Blue=15,Green=75,Red=255)。 The bottom-left pixel has (Blue=100,Green=100, Red=88).左下角的像素有(蓝色=100,绿色=100,红色=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?谁能帮我?

print() has an arg to change default ending from \\n . print()有一个 arg 来更改从\\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()

These lines of code solved my problem, thanks to user3474165 :行代码解决了我的问题,感谢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') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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