Python Forum
Formatting outputs created with .join command
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting outputs created with .join command
#2
It helps to break things up into smaller pieces.
import cv2


img = cv2.imread('test.jpg')
with open('JpgtoRGBoutput.txt', 'w') as f_out:
    offset = 0
    for row in img:
        pixels = [f'{index+offset:03},{r:03},{g:03},{b:03}' for index, (r, g, b) in enumerate(row)]
        print(','.join(pixels), file=f_out)
        offset += len(pixels)
In this code the join() and the pixel creation are split into separate statements. This might make it easer to see that the only thing join does is stitch together a sequence of strings.

To pad numbers to 3 digits with a leading zero, you add ":03" to the format. I used f'string formatting because I think it reads better than using format(). If you prefer using format.
pixels = ["{:03},{:03},{:03},{:03}".format(col+offset, *pixel) for col, pixel in enumerate(row)]
There is a problem with this code in that for any image larger than 1000 pixels, the index is larger than 3 digits. This is the last line for a 250x72 image.
Output:
17750,250,218,039,17751,245,209,0311...17998,152,118,065,17999,233,207,170
Reply


Messages In This Thread
RE: Formatting outputs created with .join command - by deanhystad - Aug-22-2023, 04:18 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  format json outputs ! evilcode1 3 1,793 Oct-29-2023, 01:30 PM
Last Post: omemoe277
  I have written a program that outputs data based on GPS signal kalle 1 1,233 Jul-22-2022, 12:10 AM
Last Post: mcmxl22
  Why does absence of print command outputs quotes in function? Mark17 2 1,438 Jan-04-2022, 07:08 PM
Last Post: ndc85430
  Thoughts on interfacing with a QR code reader that outputs keystrokes? wrybread 1 1,532 Oct-08-2021, 03:44 PM
Last Post: bowlofred
  Combining outputs into a dataframe rybina 0 1,705 Mar-15-2021, 02:43 PM
Last Post: rybina
  ONE input => THREE outputs Tricia279 6 2,749 Jan-14-2021, 08:52 AM
Last Post: perfringo
  The difference between os.path.join( and os.sep.join( Pedroski55 2 9,612 Nov-17-2020, 08:38 AM
Last Post: Pedroski55
  Multi set string inputs/outputs kwmcgreal 2 2,127 Sep-26-2020, 10:44 PM
Last Post: kwmcgreal
  How to use subprocess to get multiple data outputs in desired folder? 3SG14 1 2,276 Sep-19-2020, 05:46 PM
Last Post: bowlofred
  Outputs missing SamAnw 4 2,686 Feb-12-2020, 04:32 PM
Last Post: adetheheat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020