图像块处理

时间:2018-11-26 07:50:45

标签: python image image-processing

我的图像很大,我想一次逐块(512 x 512)对其进行处理。我目前正在使用循环执行此操作,但是我知道这不是执行此操作的最有效方法。我还能使用什么来使其更优化?

1 个答案:

答案 0 :(得分:1)

您可以将图像分为多个multiprocess.Array,在不同的过程中分别处理每个图像,然后重建图像。
这里有一些玩具示例,可以帮助您入门:

from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
import numpy as np


def processBlock(arr,i): #Image Processing function, i is an extra argument i used for the process.
    block = np.frombuffer(arr.get_obj())
    block = block.reshape((512,512,3))
    #Some processing
    block[:] = i
    ############
    block = block.reshape((-1))
    arr[:] = block


fullImage = np.zeros((512*2,512*2,3)) #Create full image of 0s
imageParts = []
imageParts.append(Array('d',fullImage[0:512,512:,:].flatten())) #Divide it into 4 parts
imageParts.append(Array('d',fullImage[0:512,0:512,:].flatten()))
imageParts.append(Array('d',fullImage[512:,0:512,:].flatten()))
imageParts.append(Array('d',fullImage[512:,512:,:].flatten()))
processes = []
for i in range(4): #Process each part simulatinously 
    p = Process(target = processBlock, args=(imageParts[i],i))
    p.start()
    processes.append(p)

for i in range(4): #Wait for all
    processes[i].join()

#Reconstruct Image
fullImage[0:512,512:,:] = np.frombuffer(imageParts[0].get_obj()).reshape((512,512,3))
fullImage[0:512,0:512,:] = np.frombuffer(imageParts[1].get_obj()).reshape((512,512,3))
fullImage[512:,0:512,:] = np.frombuffer(imageParts[2].get_obj()).reshape((512,512,3))
fullImage[512:,512:,:] = np.frombuffer(imageParts[3].get_obj()).reshape((512,512,3))