import numpy as np
import matplotlib.pyplot as plt
def subpixel_render_and_save_all(image_path):
# Load the image as an array and normalize to RGB values [0, 255]
img_arrayimg = plt.imread(image_path)
# HandleIgnore imagesalpha withchannel anfor alphanow. channelTODO ifhandle presentalpha channel
if img_arrayimg.shape[2] == 4:
img_arrayimg = img_array[img[:, :, :3]
img_array
img = (img_arrayimg * 255).astype(np.uint8)
height, width, _ = img_arrayimg.shape
# Create a base for the subpixel-rendered image (3x larger dimensions)
subpixel_arrayimg_subpixels = np.zeros((height * 3, width * 3, 3), dtype=np.uint8)
# Place each color channel in its respective vertical subpixel column
subpixel_array[img_subpixels[:, 0::3, 0] = np.repeat(img_array[img[:, :, 0], 3, axis=0) # Red
subpixel_array[img_subpixels[:, 1::3, 1] = np.repeat(img_array[img[:, :, 1], 3, axis=0) # Green
subpixel_array[img_subpixels[:, 2::3, 2] = np.repeat(img_array[img[:, :, 2], 3, axis=0) # Blue
# Derive output file names
base_filename = image_path.rsplit('.', 1)[0]
colorful_output_path = f"{base_filename}_subpixel.png"
grayscale_output_path = f"{base_filename}_subpixel_grayscale.png"
downscaled_output_path = f"{base_filename}_subpixel_grayscale_downscaled.png"
# Save the colorful subpixel-rendered image
plt.imsave(colorful_output_path, subpixel_array)
print(f"Colorful subpixel-rendered image saved to {colorful_output_path}")
# Convert to grayscale using luminance method
# grayscale_subpixel_arrayimg_subpixels_grayscale = (0.2989 * subpixel_array[img_subpixels[:, :, 0] +
# 0.5870 * subpixel_array[img_subpixels[:, :, 1] +
# 0.1140 * subpixel_array[img_subpixels[:, :, 2]).astype(np.uint8)
# Convert to grayscale
grayscale_subpixel_arrayimg_subpixels_grayscale = (subpixel_array[img_subpixels[:, :, 0] +
subpixel_array[img_subpixels[:, :, 1] +
subpixel_array[img_subpixels[:, :, 2]).astype(np.uint8)
# Save the grayscale subpixel-rendered image
plt.imsave(grayscale_output_path, grayscale_subpixel_array, cmap="gray")
print(f"Grayscale subpixel-rendered image saved to {grayscale_output_path}")
# Downscale by averaging each 3x3 block to a single pixel
downscaled_arrayimg_subpixels_grayscale_downscaled = grayscale_subpixel_arrayimg_subpixels_grayscale.reshape(height, 3, width, 3).mean(axis=(1, 3)).astype(np.uint8)
# Save thebase_filename downscaled= grayscaleimage_path.rsplit('.', image1)[0]
plt.imsave(downscaled_output_path, downscaled_arrayf"{base_filename}_subpixels.png", cmap="gray"img_subpixels)
printplt.imsave(f"Downscaledf"{base_filename}_subpixels_grayscale.png", grayscaleimg_subpixels_grayscale, imagecmap="gray")
saved to plt.imsave(f"{downscaled_output_pathbase_filename}"_subpixels_grayscale_downscaled.png", img_subpixels_grayscale_downscaled, cmap="gray")
# Example usage
subpixel_render_and_save_all("input_image.png")