pip install opencv-python-headless numpy
"""
Ghibli Style Image Converter
This script loads an image "img.png" from the current folder,
applies a cartoon/animation-inspired filter to mimic a Ghibli aesthetic,
and then saves and displays the result as "ghibli_img.png".
Requirements:
- OpenCV (cv2)
- NumPy
"""
import cv2
import numpy as np
def apply_ghibli_filter(image):
# Step 1: Smooth the image with a bilateral filter repeatedly.
# This reduces small color variations while keeping edges sharp.
filtered = image.copy()
for _ in range(7): # Adjust iterations for stronger smoothing if desired.
filtered = cv2.bilateralFilter(filtered, d=9, sigmaColor=75, sigmaSpace=75)
# Step 2: Edge detection.
# Convert to grayscale and apply a median blur.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_blur = cv2.medianBlur(gray, 7)
# Use adaptive thresholding to extract clean edges.
edges = cv2.adaptiveThreshold(
gray_blur,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
blockSize=9,
C=2
)
# Convert edges back to BGR so you can combine it with the color image.
edges_colored = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
# Combine the smoothed image with the edge mask.
cartoon = cv2.bitwise_and(filtered, edges_colored)
# Step 3: Enhance color to achieve warm, whimsical tones.
# Convert from BGR to HSV to manipulate saturation and brightness.
hsv = cv2.cvtColor(cartoon, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
# Increase saturation and brightness slightly.
s = cv2.add(s, 20)
v = cv2.add(v, 10)
final_hsv = cv2.merge((h, s, v))
# Convert back to BGR color space.
final_img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return final_img
def main():
# Load the image.
image = cv2.imread("img.png")
if image is None:
print("Error: Unable to load image 'img.png'. Please ensure the file is in this folder.")
return
# Apply the Ghibli-style filter.
result = apply_ghibli_filter(image)
# Save the resulting image.
cv2.imwrite("ghibli_img.png", result)
# Display the resulting image.
cv2.imshow("Ghibli Style Image", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
Comments
Post a Comment