将图像缩放 Python K 因子的最简单算法
Simplest algorithm for zooming an image in Python by K factor
我是 Python 的新手。
可以将图像缩放 3 倍的最简单算法是什么?
我不想使用已经可用的缩放功能。
假设您的文件系统上有一个名为 lenna.png 的 .png 图像。您可以加载它并将其转换为像这样的 numpy 数组
from PIL import Image
import numpy as np
image = np.asarray( Image.open("lenna.png") )
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()
Numpy 提供了一种简单的方法来增加像素分辨率,如下所示:
# Simply increase the resolution of the image by repeating the pixels
zoom_factor = 3
for i in range(2):
image = np.repeat(image, zoom_factor, axis=i)
如果我们绘制图像,它现在在每个维度上都有更多像素:
然后您可以像这样裁剪新的高分辨率图像,从而只显示图像的一部分
# Focus on any paricular region by croping it out
image = image[700:1000, 700:1000]
plt.imshow(image)
plt.show()
结果是这样的
干杯!
任务比较繁琐,所以我展示了一种简单的实现行缩放的方法。您也可以类似地修改索引以实现 new_image
的列索引。
# loading the image
from PIL import Image
import numpy as np
image = np.asarray( Image.open("img.jpg") )
import matplotlib.pyplot as plt
# create new image of correct size
m = len(image[0])
n = len(image)
factor = 3
new_image = np.zeros((factor*(n-1) + 1,factor*(m-1) + 1,3), dtype=int)
# implement row zooming
for i in range(n):
row = image[i]
for k in range(len(row)-1):
new_image[i][k*factor], new_image[i][(k+1)*factor] = row[k], row[k+1]
for mode in range(3):
# need mode as three colour channels in RGB
lo = int(min(row[k][mode], row[k+1][mode]))
hi = int(max(row[k][mode], row[k+1][mode]))
diff = int((hi-lo)//factor)
for x in range(factor-1):
new_image[i][k*factor+1+x][mode] = lo + (x*diff)
我是 Python 的新手。
可以将图像缩放 3 倍的最简单算法是什么? 我不想使用已经可用的缩放功能。
假设您的文件系统上有一个名为 lenna.png 的 .png 图像。您可以加载它并将其转换为像这样的 numpy 数组
from PIL import Image
import numpy as np
image = np.asarray( Image.open("lenna.png") )
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()
# Simply increase the resolution of the image by repeating the pixels
zoom_factor = 3
for i in range(2):
image = np.repeat(image, zoom_factor, axis=i)
如果我们绘制图像,它现在在每个维度上都有更多像素:
然后您可以像这样裁剪新的高分辨率图像,从而只显示图像的一部分
# Focus on any paricular region by croping it out
image = image[700:1000, 700:1000]
plt.imshow(image)
plt.show()
结果是这样的
干杯!
任务比较繁琐,所以我展示了一种简单的实现行缩放的方法。您也可以类似地修改索引以实现 new_image
的列索引。
# loading the image
from PIL import Image
import numpy as np
image = np.asarray( Image.open("img.jpg") )
import matplotlib.pyplot as plt
# create new image of correct size
m = len(image[0])
n = len(image)
factor = 3
new_image = np.zeros((factor*(n-1) + 1,factor*(m-1) + 1,3), dtype=int)
# implement row zooming
for i in range(n):
row = image[i]
for k in range(len(row)-1):
new_image[i][k*factor], new_image[i][(k+1)*factor] = row[k], row[k+1]
for mode in range(3):
# need mode as three colour channels in RGB
lo = int(min(row[k][mode], row[k+1][mode]))
hi = int(max(row[k][mode], row[k+1][mode]))
diff = int((hi-lo)//factor)
for x in range(factor-1):
new_image[i][k*factor+1+x][mode] = lo + (x*diff)