PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, May 7, 2022

[FIXED] How to read an Unsigned Char image file to Python?

 May 07, 2022     file-type, image, image-processing, unsigned-char     No comments   

Issue

I have an text file called with the extension '.image', at the top of the file is the following:

Image Type: unsigned char
Dimension: 2
Image Size: 512 512
Image Spacing: 1 1
Image Increment: 1 1
Image Axis Labels: "" "" 
Image Intensity Label: ""
193

I believe this to be an unsigned char file, but i'm having a hard time opening it in python (and saving it as a jpg, png etc)

Have tried the standard PIL.Image.open(), saving as a string and reading with Image.fromstring('RGB', (512,512), string), and reading as byte-like object Image.open(io.BytesIO(filepath))

Any ideas? Thanks in advance


Solution

If we assume there is some arbitrary, unknown length header on the file, we can read the entire file and then rather than parsing the header, just take the final 512x512 bytes from the tail of the file:

#!/usr/bin/env python3

from PIL import Image
import pathlib

# Slurp the entire contents of the file
f = pathlib.Path('image.raw').read_bytes()

# Specify height and width
h, w = 512, 512

# Take final h*w bytes from the tail of the file and treat as greyscale values, i.e. mode='L'
im = Image.frombuffer('L', (w,h), f[-(h*w):], "raw", 'L', 0, 1)

# Save to disk
im.save('result.png')

Or, if you prefer Numpy to Pathlib:

#!/usr/bin/env python3

from PIL import Image
import numpy as np

# Specify height and width
h, w = 512, 512

# Slurp entire file into Numpy array, take final 512x512 bytes, and reshape to 512x512
na = np.fromfile('image.raw', dtype=np.uint8)[-(h*w):].reshape((h,w))

# Make Numpy array into PIL Image and save
Image.fromarray(na).save('result.png')

Or, if you don't really fancy writing any Python, just use tail in Terminal to slice the last 512x512 bytes off your file and tell ImageMagick to make an 8-bit PNG from the grayscale byte values:

tail -c $((512*512)) image.raw | magick -depth 8 -size 512x512  gray:- result.png


Answered By - Mark Setchell
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing