Skip to content

Instantly share code, notes, and snippets.

@MeherajUlMahmmud
Created July 24, 2023 09:34
Show Gist options
  • Save MeherajUlMahmmud/e59e7bb2c39f066bb3a8695fe34d5bcc to your computer and use it in GitHub Desktop.
Save MeherajUlMahmmud/e59e7bb2c39f066bb3a8695fe34d5bcc to your computer and use it in GitHub Desktop.
This script will pad an image with the common color. It will add extra space on all four sides of an image
import cv2
import numpy as np
def pad_image(image, padding_percent):
"""
Pad the image and return it
:param image: Numpy array
:param padding_percent: float
:return: padded_image: Numpy array
"""
# Find the most common color in the image
most_common_color = find_most_common_color(image)
if padding_percent < 0 or padding_percent > 1:
padding_percent = 0.2
desired_height = int(image.shape[0] * (2 + padding_percent))
desired_width = int(image.shape[1] * (1 + padding_percent))
# Determine the dimensions of the original image
original_height, original_width = image.shape[:2]
# Create a new padded image array with the desired dimensions
padded_image = np.full((desired_height, desired_width, 3),
fill_value=most_common_color, dtype=np.uint8)
# Calculate the position to place the original image in the center of the padded image
start_height = (desired_height - original_height) // 2
start_width = (desired_width - original_width) // 2
# Place the original image in the center of the padded image
padded_image[start_height:start_height + original_height,
start_width:start_width + original_width] = image
return padded_image
def find_most_common_color(image):
"""
Find the most common color in the image and return it
:param image: Numpy array
:return: most_common_color: tuple
"""
# Flatten the image into a 2D array of pixels
pixels = image.reshape(-1, 3)
# Count the occurrence of each unique color value
color_counts = np.unique(pixels, axis=0, return_counts=True)
# Find the index of the color with the highest count
most_common_index = np.argmax(color_counts[1])
# Retrieve the most common color from the index
most_common_color = color_counts[0][most_common_index]
return tuple(most_common_color)
img_path = 'input_img_path.jpg'
img = cv2.imread(img_path)
img = pad_image(img, 0.2)
cv2.imwrite('output_img_path.jpg', img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment