Skip to content

Instantly share code, notes, and snippets.

@gledos
Created May 22, 2024 08:16
Show Gist options
  • Save gledos/aa7c98b53b8eb73670dc0462656c1a10 to your computer and use it in GitHub Desktop.
Save gledos/aa7c98b53b8eb73670dc0462656c1a10 to your computer and use it in GitHub Desktop.
restored pixel art Python script
#!/usr/bin/env python
"""\
This script is from Returning Pixel Art to their original size by Antonio Neves. Written for Python via ChatGPT-4o.
Original: Retrieving the original pixel size for digital arts and NFTs
<https://community.wolfram.com/groups/-/m/t/2407109>
---
该脚本,来自 Antonio Neves 的 Returning Pixel Art to their original size。经过 ChatGPT-4o 编写为了 Python 版本。
原始手册:Retrieving the original pixel size for digital arts and NFTs
<https://community.wolfram.com/groups/-/m/t/2407109>
Usage: python restored_pixel_art.py path/to/pixle/art.png
"""
import numpy as np
from PIL import Image, ImageOps
import sys
def restore_pixel_art(image_path):
# read image
# 读取图像
input_image = Image.open(image_path)
# Convert to grayscale image for Fourier transform
# 转换为灰度图像以进行傅立叶变换
gray_image = ImageOps.grayscale(input_image)
# Convert grayscale image to NumPy array
# 将灰度图像转换为 NumPy 数组
gray_image_np = np.array(gray_image)
# Perform Fourier transform
# 进行傅立叶变换
f_transform = np.fft.fft2(gray_image_np)
f_shift = np.fft.fftshift(f_transform)
magnitude_spectrum = np.log(np.abs(f_shift) + 1)
# Get image center
# 获取图像中心
rows, cols = gray_image_np.shape
crow, ccol = rows // 2, cols // 2
# Take a quarter of the spectrum
# 取四分之一大小的频谱
adjusted_spectrum = f_shift[crow - rows // 4:crow + rows // 4, ccol - cols // 4:ccol + cols // 4]
# Calculate the horizontal and vertical projection
# 计算水平和垂直方向上的投影
horizontal_projection = np.sum(np.abs(adjusted_spectrum), axis=0)
vertical_projection = np.sum(np.abs(adjusted_spectrum), axis=1)
# Background removal
# 背景去除
horizontal_projection -= np.min(horizontal_projection)
vertical_projection -= np.min(vertical_projection)
# Find the maximum peak value
# 找到最大峰值
h_peak = np.argmax(horizontal_projection)
v_peak = np.argmax(vertical_projection)
# Calculate scaling ratio
# 计算缩放比例
scaling_factor_h = cols / h_peak
scaling_factor_v = rows / v_peak
scaling_factor = min(scaling_factor_h, scaling_factor_v)
# Reduce the original image
# 缩小原图像
new_size = (int(cols / scaling_factor), int(rows / scaling_factor))
resized_image = input_image.resize(new_size, Image.NEAREST)
# Save results
# 保存结果
output_image_path = f"{image_path.split('.')[0]}_restored.png"
resized_image.save(output_image_path)
print(f"The restored image was saved as {output_image_path}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python restored_pixel_art.py path/to/pexel/art.png")
sys.exit(1)
image_path = sys.argv[1]
restore_pixel_art(image_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment