<jupyter_start><jupyter_text><jupyter_code># https://zhuanlan.zhihu.com/p/336544299

import numpy as np
from PIL import Image, ImageFont, ImageDraw
from PIL.ImageChops import add, subtract, multiply, difference, screen
import PIL.ImageStat as stat
from skimage.io import imread, imsave, imshow, show, imread_collection, imshow_collection
from skimage import color, viewer, exposure, img_as_float, data
from skimage.transform import SimilarityTransform, warp, swirl
from skimage.util import invert, random_noise, montage
import matplotlib.image as mpimg
import matplotlib.pylab as plt
from scipy.ndimage import affine_transform, zoom
from scipy import misc

im = Image.open("./images/parrot.jpg") # read the image, provide the correct path
print(im.width, im.height, im.mode, im.format, type(im))
# 453 340 RGB PNG <class 'PIL.PngImagePlugin.PngImageFile'>
im.show() # display the image
im_g = im.convert('L') # convert the RGB color image to a grayscale image
im_g.save('./images/parrot_gray.png') # save the image to disk
Image.open("./images/parrot_gray.png").show() # read the grayscale image from disk and show

im = mpimg.imread("./images/lena_small.png") # read the image from disk as a numpy ndarray
methods = ['none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'lanczos']
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 30),subplot_kw={'xticks': [],
'yticks': []})
fig.subplots_adjust(hspace=0.05, wspace=0.05)
for ax, interp_method in zip(axes.flat, methods):
    ax.imshow(im, interpolation=interp_method)
    ax.set_title(str(interp_method), size=20)
plt.tight_layout()
plt.show()
plt.imshow(im, interpolation='bilinear')
plt.tight_layout()
plt.show()
def img_resize(img, mag=1, method='nearest'):
    mag = float(mag) # 将倍率强制转换为浮点数
    height, width = img.shape[0], img.shape[1] # 获取原图的高和宽
    new_h, new_w = int(height * mag), int(width * mag) # 计算新图的高和宽
    new_img = np.zeros((new_h,new_w,3)) # 初始化新图的张量

    # 最临近值插值
    if method == 'nearest':
        # 遍历每个新图的像素点，在这里高坐标代表y轴坐标，宽坐标代表x轴坐标
        for new_h_y in range(new_h):
            for new_h_x in range(new_w):
                # 原来的宽、高坐标与新坐标的关系是有一个倍率的整数
                w_x = int(new_h_x / mag)
                h_y = int(new_h_y / mag)
                # 在新图该位置赋值
                new_img[new_h_y, new_h_x] = img[h_y, w_x]
        return new_img


    # 双线性插值
    elif method == 'bilinear':
        # 遍历每个新图的像素点
        for new_h_y in range(new_h):
            for new_h_x in range(new_w):
                # 将每个像素看做正方形，进行中心对齐，投影目标图的横轴和纵轴到原图上
                w_x = (new_h_x + 0.5) / mag - 0.5
                h_y = (new_h_y +0.5) / mag - 0.5

                # 找出每个投影点在原图横轴方向的近邻点坐标
                # 原图范围是0~width-2, 0~height-2是因为要考虑+1后的边界
                f_x = np.clip(w_x, 0, width-2).astype(np.int)
                f_y = np.clip(h_y, 0, height-2).astype(np.int)

                # 给出原轴的4个最近邻点Q坐标
                x1, x2 = f_x, f_x+1
                y1, y2 = f_y, f_y+1

                # 给出这四个Q点对应的权重，注意图像数据中y轴在第一位，x轴在第二位
                f_Q11 = img[y1, x1]
                f_Q12 = img[y2, x1]
                f_Q21 = img[y1, x2]
                f_Q22 = img[y2, x2]

                # 计算两个R点对应的权重
                f_R1 = (x2 - w_x) / (x2 - x1)*f_Q11 + (w_x - x1) / (x2 - x1)*f_Q21
                f_R2 = (x2 - w_x) / (x2 - x1)*f_Q12 + (w_x - x1) / (x2 - x1)*f_Q22

                # 计算投影点P的双线性插值，将其赋值于新图该点像素
                f_P = (y2 - h_y) / (y2 - y1)*f_R1 + (h_y - y1) / (y2 - y1)*f_R2
                new_img[new_h_y, new_h_x] = f_P
        return new_img






neIm1 = img_resize(im, mag=2)
plt.imshow(neIm1)
neIm2 = img_resize(im, mag=2, method='bilinear')
plt.imshow(neIm2)

print("colab output")<jupyter_output>colab output
{'fraction_non_alphanumeric': 0.1247978436657682, 'fraction_numerical': 0.029919137466307276, 'mean_word_length': 2.5511961722488037, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '285965', 'license': 'Apache-2.0', 'n_tokens_mistral': 1691, 'n_tokens_neox': 1669, 'n_words': 315, 'path': 'Test1/Test1.ipynb', 'repo_name': 'Alephant6/Digital_imaging_processing', 'size': '3710'}