Skip to content

Instantly share code, notes, and snippets.

@bjonnh
Created November 15, 2024 23:30
Show Gist options
  • Save bjonnh/a13f1928d852954dac86cc1542a7340f to your computer and use it in GitHub Desktop.
Save bjonnh/a13f1928d852954dac86cc1542a7340f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Usage:
# To convert:
# ./display_raw.py thingy.raw --convert more_accessible_thingy.tiff
# To display:
# ./display_raw.py thingy.raw
import numpy as np
import matplotlib.pyplot as plt
import argparse
from PIL import Image
def process_raw_image(input_filename, output_filename=None, keep_header=False):
try:
raw_data = np.fromfile(input_filename, dtype=np.uint16)
total_pixels = len(raw_data)
width = 2048
with_header_height = 2148
without_header_height = 2048
header_height = with_header_height - without_header_height
if total_pixels >= width * with_header_height:
print(f"Info: Found info panel ({header_height} pixels height)")
if not keep_header:
print(f"Info: Skipping info panel (use --keep-header to include it)")
raw_data = raw_data[width*header_height:width*(header_height+without_header_height)]
elif total_pixels >= width * without_header_height:
raw_data = raw_data[0:width*without_header_height]
else:
print(f"Warning: File too small, truncating")
height = with_header_height if keep_header and total_pixels >= width * with_header_height else without_header_height
image = raw_data[0:width*height].reshape((height, width)).astype(np.uint16)
if output_filename:
im = Image.fromarray(image, mode='I;16')
im.save(output_filename, format='TIFF')
else:
plt.figure(figsize=(10, 10))
plt.imshow(image, cmap='gray')
plt.colorbar(label='Intensity')
plt.title(f'{width}x{height} 16-bit Raw Image')
plt.show()
except FileNotFoundError:
print(f"Error: File '{input_filename}' not found")
except Exception as e:
print(f"Error: {e}")
def main():
parser = argparse.ArgumentParser(description='Display or convert 2048x2048 16-bit raw image')
parser.add_argument('input', help='Input raw image file')
parser.add_argument('--convert', nargs=1, metavar='OUTPUT', help='Convert to TIFF file')
parser.add_argument('--keep-header', action='store_true', help='Keep the 100-pixel height info panel if present')
args = parser.parse_args()
process_raw_image(args.input, args.convert[0] if args.convert else None, args.keep_header)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment