最近看了双线性插值的算法,想要自己实现以下,于是写了一个程序,测了下时间,将1080*1564的一张证件照通过插值resize到600*800花了15s....
于是想要用threading多线程来做,3个子线程对3个通道分别做插值,岂不是速度会提升3倍?结果还是15s,让我实在想不通,最后查了下关于python多线程的问题,才明白过来
from PIL import Image
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import math
import os
from threading import Thread
from multiprocessing import Process
img_path = r'C:\Users\king\Pictures\简历\微信图片_20190731154219.jpg'
img_arr = np.array(Image.open(img_path), np.uint8)
target_size = (800, 600, 3)
global resized_img
resized_img = np.zeros(target_size)
cur_size = img_arr.shape
ratio_x, ratio_y = target_size[0] / cur_size[0], target_size[1] / cur_size[1]
def cal(i, j, x, y, c):
global resized_img
# print('this is the thread {}'.format(c))
t_left_x, t_left_y = math.floor(x), math.floor(y)
p1 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y, c]
p2 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y+1, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y+1, c]
v = (t_left_y+1 - y)*p1 + (y - t_left_y)*p2
resized_img[i, j, c] = v
def bilinear(c):
a = [cal(i, j, i/ratio_x, j/ratio_y, c) for i in range(target_size[0]) for j in range(target_size[1])]
if __name__ == '__main__':
start = datetime.now()
threads = []
for c in range(3):
t = Thread(target=bilinear, args=(c,))
threads.append(t)
t.start()
for t in threads:
t.join()
# print(resized_img)
end = datetime.now()
seconds = (end-start).seconds
print('process cost {}s'.format(seconds))
resized_show = Image.fromarray(resized_img.astype(np.uint8))
plt.imshow(resized_show)
plt.show()
因为在python的世界里,不得不提GIL(Global Interpreter Lock),由于其存在,每个CPU时间内只能执行一个线程,所以单核CPU下的python多线程只能处理并发而不能处理并行。
在python中, GIL的释放逻辑是当遇到IO操作或者ticks技术达到阈值,GIL释放,其他线程被唤醒,将要竞争拿到GIL上CPU运行,这种竞争模式可能是先来先服务,短作业优先或者时间片轮转...