Skip to content

Instantly share code, notes, and snippets.

@e96031413
Created April 12, 2023 09:05
Show Gist options
  • Save e96031413/c98d856a2b2baa01f062d98cd74c16e2 to your computer and use it in GitHub Desktop.
Save e96031413/c98d856a2b2baa01f062d98cd74c16e2 to your computer and use it in GitHub Desktop.
Visualizing the PASCALRAW nef format image with OpenCV and rawpy
import cv2
import imageio
import rawpy
class RawImage:
"""
A class for working with raw image files.
Attributes:
file_path (str): The path to the raw image file.
raw: The rawpy object representing the raw image.
"""
def __init__(self, file_path):
"""
Initializes a RawImage object.
Args:
file_path (str): The path to the raw image file.
"""
self.file_path = file_path.lower()
self.raw = None
def load_raw_image(self):
"""
Loads the raw image from the file.
"""
self.raw = rawpy.imread(self.file_path) if "nef" in self.file_path else imageio.v2.imread(self.file_path)
def get_rgb_image(self):
"""
Returns an RGB image from the raw image, after applying color transformation matrix.
Returns:
numpy.ndarray: The RGB image.
"""
rgb = self.raw.postprocess(use_camera_wb=False, gamma=(2.2, 2.2), no_auto_bright=False, output_bps=16, half_size=False)
return cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB)
def show_resized_image(self, window_size=(600, 400)):
"""
Shows a resized version of the RGB image in a window.
Args:
window_size (tuple, optional): The desired size of the window. Defaults to (600, 400).
"""
rgb = self.get_rgb_image()
h, w = rgb.shape[:2]
# Calculate the scaling factor to fit the image into the window
scaling_factor = min(window_size[0] / w, window_size[1] / h)
# Calculate the new dimensions of the image after scaling
new_size = (int(w * scaling_factor), int(h * scaling_factor))
# Resize the image to fit the window
resized_img = cv2.resize(rgb, new_size)
# Create a window with the desired size
cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Image', window_size)
# Show the resized image in the window
cv2.imshow('Image', resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
file_path = "2014_000001.nef"
raw_image = RawImage(file_path)
raw_image.load_raw_image()
raw_image.show_resized_image()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment