Last active
March 8, 2025 19:12
-
-
Save yuchen-xue/3c30a4dcd96a6c4dc0e2ee6e4c5d21e2 to your computer and use it in GitHub Desktop.
This program reads images from a folder named "images" and produces a long image by stacking those images together.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /// script | |
# requires-python = ">=3.4" | |
# dependencies = [ | |
# "opencv-python", | |
# ] | |
# /// | |
from pathlib import Path | |
import cv2 | |
import numpy as np | |
def fit_resize(img: np.ndarray, new_width: int) -> np.ndarray: | |
"""Resize the image to the new width, keeping the aspect ratio. | |
Args: | |
img (np.ndarray): input image | |
new_width (int): new width of the output image | |
Returns: | |
np.ndarray: resized image | |
""" | |
height, width = img.shape[:2] | |
new_height = height**2 // width | |
return cv2.resize(img, (new_width, new_height)) | |
def main(img_dir: Path) -> None: | |
"""Main function to resize images and stack them horizontally. | |
Args: | |
img_dir (Path): Path to the directory containing images. | |
""" | |
# A container for all the images | |
img_list: list[np.ndarray] = list() | |
# Match ".jpg" and ".jpeg" | |
for f in img_dir.glob("*.jp*g"): | |
img = cv2.imread(str(f)) | |
img_list.append(img) | |
# Get the minimum width of all the images | |
min_width = min(img.shape[1] for img in img_list) | |
# Resize all oversized images to the minimum width, and stack them horizontally | |
output = cv2.vconcat( | |
tuple( | |
fit_resize(img, min_width) for img in img_list if img.shape[1] > min_width | |
) | |
) | |
cv2.imwrite("output.jpg", output) | |
if __name__ == "__main__": | |
# Run the main function with the "images" directory | |
main(Path("images")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment