如何使用python将正方形图像像素化为256大像素?
我需要找到一种方法,使用python将正方形图像减少到256个大像素,最好使用matplotlib和pillow库如何使用python将正方形图像像素化为256大像素?,python,image,matplotlib,pillow,Python,Image,Matplotlib,Pillow,我需要找到一种方法,使用python将正方形图像减少到256个大像素,最好使用matplotlib和pillow库 有什么想法吗?对不起,我不能给你一个Python解决方案,但我可以在命令行中使用ImageMagick向你展示技术和结果: 从这一点开始: 首先,使用普通立方或双线性插值将图像大小调整为16x16像素,然后使用“最近邻”插值将图像缩放回原始大小: convert paddington.png -resize 16x16 -scale 400x400 result.png 关键
有什么想法吗?对不起,我不能给你一个Python解决方案,但我可以在命令行中使用ImageMagick向你展示技术和结果: 从这一点开始: 首先,使用普通立方或双线性插值将图像大小调整为16x16像素,然后使用“最近邻”插值将图像缩放回原始大小:
convert paddington.png -resize 16x16 -scale 400x400 result.png
关键词:
像素化、像素化、像素化、像素化、Paddington、ImageMagick、命令行、命令行、图像、图像处理、最近邻插值。九个月过去了,我现在可以根据您最初的要求拼凑一些Python—关于如何使用Python和PIL/Pillow对图像进行像素化
#!/usr/local/bin/python3
from PIL import Image
# Open Paddington
img = Image.open("paddington.png")
# Resize smoothly down to 16x16 pixels
imgSmall = img.resize((16,16),resample=Image.BILINEAR)
# Scale back up using NEAREST to original size
result = imgSmall.resize(img.size,Image.NEAREST)
# Save
result.save('result.png')
原始图像
结果
帕丁顿太可爱了——他只需要被像素化 如果您将其缩小到32x32像素(而不是16x16像素),然后重新调整大小,您将得到: 关键词: 像素化、像素化、像素化、像素化、帕丁顿、Python、枕头、PIL、图像、图像处理、最近邻插值。另一个选项是使用 Python脚本,在Lab colorspace中使用K-Means聚类对图像和视频进行像素化。视频像素化支持多处理以实现更好的性能 使用Paddington映像作为源,您可以运行:
python pypxl_image.py -s 16 16 paddington.png paddington_pixelated.png
这就产生了这个结果
当然,如果您希望它具有256 x 256像素,而不是256个大像素,您可以运行
python pypxl_image.py -s 256 256 paddington.png paddington_pixelated.png
这就产生了这个结果
与其他解决方案相比,这两个结果都具有更复古的8位外观,可能适合您的需要。这是我的解决方案
import numpy as np
import matplotlib.pyplot as plt
def pixelate_rgb(img, window):
n, m, _ = img.shape
n, m = n - n % window, m - m % window
img1 = np.zeros((n, m, 3))
for x in range(0, n, window):
for y in range(0, m, window):
img1[x:x+window,y:y+window] = img[x:x+window,y:y+window].mean(axis=(0,1))
return img1
img = plt.imread('test.png')
fig, ax = plt.subplots(1, 4, figsize=(20,10))
ax[0].imshow(pixelate_rgb(img, 5))
ax[1].imshow(pixelate_rgb(img, 10))
ax[2].imshow(pixelate_rgb(img, 20))
ax[3].imshow(pixelate_rgb(img, 30))
# remove frames
[a.set_axis_off() for a in ax.flatten()]
plt.subplots_adjust(wspace=0.03, hspace=0)
还有一个想法是处理灰度图像:
def pixelate_bin(img, window, threshold):
n, m = img.shape
n, m = n - n % window, m - m % window
img1 = np.zeros((n,m))
for x in range(0, n, window):
for y in range(0, m, window):
if img[x:x+window,y:y+window].mean() > threshold:
img1[x:x+window,y:y+window] = 1
return img1
# convert image to grayscale
img = np.dot(plt.imread('test.png'), [0.299 , 0.587, 0.114])
fig, ax = plt.subplots(1, 3, figsize=(15,10))
plt.tight_layout()
ax[0].imshow(pixelate_bin(img, 5, .2), cmap='gray')
ax[1].imshow(pixelate_bin(img, 5, .3), cmap='gray')
ax[2].imshow(pixelate_bin(img, 5, .45), cmap='gray')
# remove frames
[a.set_axis_off() for a in ax.flatten()]
plt.subplots_adjust(wspace=0.03, hspace=0)
请记住:
png
的值介于0和1之间,而jpg
的值介于0和255之间什么是“大像素”?是否只想将图像大小调整为16x16像素?使用默认插值将其大小调整为16x16,使用最近邻插值将其缩放回原始大小。如果有人喜欢像素化图像,这只是为了好玩。。。