Picture display [numpy processing, Matplotlib display]

Time:2022-5-10

Document establishment date: March 14, 2020

Last revision date: 2020 / 04 / 05 content format adjustment

Relevant software information:

Win10 Python 3.7.6 Requests 2.23.0 Matplotlib 3.2.0 Numpy 1.18.1 Pillow 7.0.0

Note: please quote or change this article at will. Just indicate the source and author. The author does not guarantee that the content is absolutely correct. Please be responsible for any consequences

Title: image display [numpy processing, Matplotlib display]

PIL (pilot) can be used for image processing, because it is not a static image to be processed, and it is not likely to move the content of the image. In addition, it is a little unfamiliar with numpy. Therefore, numpy is used for the segmentation of the whole film, so that I can have a deeper understanding of the use of numpy

  1. target

    • Present a picture in various ways
    • There are many ways. At present, only the following are available
      • Brightness change
      • Rolling or dragging type
      • Circular display
      • Square display
      • Random expansion
    • The processing of all pictures can only make numpy (occasionally to the list)
  2. Exhibition

Picture display [numpy processing, Matplotlib display]

  1. Code and description

    • Import of related libraries
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from time import sleep
import random
import requests
from io import BytesIO
  • The picture is displayed from black to white

    The values in the array (i.e. R, G, b) change from (0, 0, 0) to (R, G, b) according to the proportion of the colors of each point. This will only change the brightness, not the color

def black_to_show(array, interval, mode=0):
    for i in range(interval, -1, -1):
        yield array-array*i/interval
  • There are 8 modes to display pictures in a square way. It is mainly to judge the square according to the index value of each point, and then use the Boolean value as the array index of pictures Although the content of the function is long, the content of the eight modes is similar
def box(array, interval, mode):
    h, w = array.shape[0], array.shape[1]
    half = int(interval/2)
    y0 = np.linspace(0, array.shape[0], interval)
    x0 = np.linspace(0, array.shape[1], interval)
    filter = np.indices(array.shape[0:2])
    im_blank = np.full(array.shape, 255, dtype=np.float)
    if mode == 0:
        for x, y in zip(x0, y0):
            check = np.logical_and(filter[0]<=y, filter[1]<=x)
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 1:
        for x, y in zip(x0[::-1], y0[::-1]):
            check = np.logical_and(filter[0]>=y, filter[1]>=x)
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 2:
        for x, y in zip(x0, y0[::-1]):
            check = np.logical_and(filter[0]>=y, filter[1]<=x)
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 3:
        for x, y in zip(x0[::-1], y0):
            check = np.logical_and(filter[0]<=y, filter[1]>=x)
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 4:
        for x, y in zip(x0[half:], y0[half:]):
            check = np.logical_and(
                np.logical_and(h-y<=filter[0], filter[0]<=y),
                np.logical_and(w-x<=filter[1], filter[1]<=x))
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 5:
        for x, y in zip(x0[half:], y0[half:]):
            check = np.logical_or(
                np.logical_and(h-y<=filter[0], filter[0]<=y),
                np.logical_and(w-x<=filter[1], filter[1]<=x))
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 6:
        for x, y in zip(x0[::-1][:half], y0[::-1][:half]):
            check = np.logical_or(
                np.logical_or(filter[0]>=y, filter[0]<=h-y),
                np.logical_or(filter[1]>=x, filter[1]<=w-x))
            im_blank[check] = array[check]
            yield im_blank
    elif mode == 7:
        for x, y in zip(x0[::-1][:half], y0[::-1][:half]):
            check = np.logical_and(
                np.logical_or(filter[0]>=y, filter[0]<=h-y),
                np.logical_or(filter[1]>=x, filter[1]<=w-x))
            im_blank[check] = array[check]
            yield im_blank
  • Circular display can be divided into two types: outward and inward or inward and outward The processing method judges the distance from each point to the center point, calculates the distance of all points in advance, and then takes the Boolean array as the index of the image array
def circle(array, interval, mode=0):
    h, w = array.shape[0]/2, array.shape[1]/2
    value = (((np.arange(array.shape[0])-h)**2)[:, None] +
              (np.arange(array.shape[1])-w)**2)
    m = np.max(value)
    radius = np.linspace(0, m, interval)
    im_blank = np.full(array.shape, 255, dtype=np.float)
    if mode == 0:
        for r in radius:
            im_blank[value<=r,:] = im_np[value<=r,:]
            yield im_blank
    else:
        for r in radius[::-1]:
            im_blank[value>=r,:] = im_np[value>=r,:]
            yield im_blank
  • Block random display, simple picture subarray replacement
def random_block(array, interval, mode=0):
    im_blank = np.full(array.shape, 255, dtype=np.float)
    y = np.linspace(0, array.shape[0], interval+1).astype(np.int)
    x = np.linspace(0, array.shape[1], interval+1).astype(np.int)
    where = [(i, j) for i in range(interval) for j in range(interval)]
    np.random.shuffle(where)
    for i, j in where:
        im_blank[y[j]:y[j+1], x[i]:x[i+1]] = array[y[j]:y[j+1], x[i]:x[i+1]]
        yield im_blank
  • There are also eight ways of scrolling picture display, four directions (up, down, left, right), and dragging or displaying This part is simpler, just substituting the subarray of the picture
def scroll(array, interval, mode=0):
    im_blank = np.full(array.shape, 255, dtype=np.float)
    if mode < 4:
        for i in np.linspace(1, array.shape[1]-1, interval):
            if mode == 0:
                im_blank[:, :int(i)] = array[:, :int(i)]
            elif mode == 1:
                im_blank[:, :int(i)] = array[:, -int(i):]
            elif mode == 2:
                im_blank[:, -int(i):] = array[:, :int(i)]
            elif mode == 3:
                im_blank[:, -int(i):] = array[:, -int(i):]
            yield im_blank
    else:
        for i in np.linspace(1, array.shape[0]-1, interval):
            if mode == 4:
                im_blank[:int(i)] = array[:int(i)]
            elif mode == 5:
                im_blank[:int(i)] = array[-int(i):]
            elif mode == 6:
                im_blank[-int(i):] = array[:int(i)]
            elif mode == 7:
                im_blank[-int(i):] = array[-int(i):]
            yield im_blank
  • The picture is displayed from white to white

    The values in the array (i.e. R, G and b) change from (255, 255, 255) to (R, G and b) according to the proportion of the colors of each point. This will only change the brightness, not the color

def white_to_show(array, interval, mode=0):
    for i in range(interval, -1, -1):
        yield array+i*(255 - array)/interval
  • Display function

    Call the relevant functions and set the interval and mode. Because of the time relationship, each function adopts yield to iterate the output, and set in matplot_ Data does not need to delete the drawn image_ The idle function is used to update, and pause is used to pause to update the picture

def show(func, array, interval, mode=0):
    for data in func(array, interval, mode):
        im_plt.set_data(np.clip(data.astype(int), 0, 255))
        fig.canvas.draw_idle()
        plt.pause(0.001)
  • Loading of pictures

    In order to avoid the need for additional picture files, download a picture directly from the web page for the whole process

url = 'https://p2.bahamut.com.tw/WIKI/82/00365182.JPG'
response = requests.get(url)
im = Image.open(BytesIO(response.content))
im_np = np.array(im, dtype=np.float)
  • In the initial implementation of Matplotlib, the coordinate axis is mainly hidden
fig,ax = plt.subplots(1,1)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
im_plt = ax.imshow(np.full(im_np.shape, 255))
  • Display the display function of each function
show(white_to_show, im_np, 10)
show(black_to_show, im_np, 10)
for mode in range(8):
    show(scroll, im_np, 10, mode=mode)
show(random_block, im_np, 5)
show(circle, im_np, 20, mode=0)
show(circle, im_np, 20, mode=1)
for mode in range(4, 8):
    show(box, im_np, 20, mode=mode)
  • Close drawing interface
plt.close()

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Jason Yang