Python快速批修改PNGs

2024-05-29 04:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我为OpenGL着色器编写了一个python脚本,它以独特的方式组合图像。问题是我有大量非常大的地图,需要很长时间来处理。有没有一种更快的方式来写这篇文章?在

    import numpy as np

    map_data = {}
    image_data = {}
    for map_postfix in names:
    file_name = inputRoot + '-' + map_postfix + resolution + '.png'
    print 'Loading ' + file_name
    image_data[map_postfix] = Image.open(file_name, 'r')
    map_data[map_postfix] = image_data[map_postfix].load()


    color = mapData['ColorOnly']
    ambient = mapData['AmbientLight']
    shine = mapData['Shininess']

    width = imageData['ColorOnly'].size[0]
    height = imageData['ColorOnly'].size[1]

    arr = np.zeros((height, width, 4), dtype=int)

    for i in range(width):
        for j in range(height):
            ambient_mod = ambient[i,j][0] / 255.0
            arr[j, i, :] = [color[i,j][0] * ambient_mod , color[i,j][1] * ambient_mod , color[i,j][2] * ambient_mod , shine[i,j][0]]

    print 'Converting Color Map to image'
    return Image.fromarray(arr.astype(np.uint8))

这只是大量批处理过程的一个示例,所以我更感兴趣的是是否有一种更快的方法来迭代和修改图像文件。几乎所有的时间都花在嵌套循环与加载和保存上。在


Tags: nameinimagemodmapfordatanp
1条回答
网友
1楼 · 发布于 2024-05-29 04:24:22

timeitzmq.Stopwatch()中对你的向量化代码示例测试效果

Reported to have 22.14 seconds >> 0.1624 seconds speedup!

虽然您的代码似乎只是在RGBA[x,y]上循环,但让我展示一个“向量化”—代码的语法,它受益于numpy矩阵操作工具(忘记RGB/YUV操作(最初基于OpenCV而不是PIL),但是重复使用向量化语法方法,以避免for循环和调整它以有效地为你的微积分工作。错误的操作顺序可能会使处理时间加倍。在

并使用测试/优化/重新测试环路加速。在

对于测试,如果[msec]分辨率足够,则使用标准pythontimeit。在

如果您需要进入[usec]分辨率,请选择zmq.StopWatch()。在

# Vectorised-code example, to see the syntax & principles
#                          do not mind another order of RGB->BRG layers
#                          it has been OpenCV traditional convention
#                          it has no other meaning in this demo of VECTORISED code

def get_YUV_U_Cb_Rec709_BRG_frame( brgFRAME ):  # For the Rec. 709 primaries used in gamma-corrected sRGB, fast, VECTORISED MUL/ADD CODE
    out =  numpy.zeros(            brgFRAME.shape[0:2] )
    out -= 0.09991 / 255 *         brgFRAME[:,:,1]  # // Red
    out -= 0.33601 / 255 *         brgFRAME[:,:,2]  # // Green
    out += 0.436   / 255 *         brgFRAME[:,:,0]  # // Blue
    return out
# normalise to <0.0 - 1.0> before vectorised MUL/ADD, saves [usec] ...
# on 480x640 [px] faster goes about 2.2 [msec] instead of 5.4 [msec]

在您的例子中,使用dtype = numpy.int,猜测先用ambient[:,:,0]MUL,最后DIV使{}正常化会更快

^{pr2}$

那么它在你的算法中会是什么样子?

一个人不需要拥有彼得·杰克逊令人印象深刻的预算和时间一旦计划、跨越和执行大量的数字运算,他在新西兰的一个机库里,被一群SGI工作站挤得水泄不通,因为他正在生产“指环王”全数字母板装配线,通过逐帧像素操作,意识到量产流水线中的毫秒、微秒甚至纳秒都很重要。

因此,深呼吸,测试并重新测试,以便将您的真实世界图像处理性能优化到您的项目需要的水平。在

希望这对您有所帮助:

# OPTIONAL for performance testing       -# ||||||||||||||||||||||||||||||||
from zmq import Stopwatch                       # _MICROSECOND_ timer
#                                               # timer-resolution step ~ 21 nsec
#                                               # Yes, NANOSECOND-s
# OPTIONAL for performance testing       -# ||||||||||||||||||||||||||||||||
arr        = np.zeros( ( height, width, 4 ), dtype = int )
aStopWatch = zmq.Stopwatch()                    # ||||||||||||||||||||||||||||||||
# /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# <<< your original code segment          
#  aStopWatch.start()                           # |||||||||||||__.start
#  for i in range(     width  ):
#      for j in range( height ):
#          ambient_mod  = ambient[i,j][0] / 255.0
#          arr[j, i, :] = [ color[i,j][0] * ambient_mod, \
#                           color[i,j][1] * ambient_mod, \
#                           color[i,j][2] * ambient_mod, \
#                           shine[i,j][0]                \
#                           ]
#  usec_for = aStopWatch.stop()                 # |||||||||||||__.stop
#  print 'Converting Color Map to image'
#  print '           FOR processing took ', usec_for, ' [usec]'
# /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# <<< proposed alternative
aStopWatch.start()                              # |||||||||||||__.start
# reduced numpy broadcasting one dimension less # ref. comments below
arr[:,:, 0]  = color[:,:,0] * ambient[:,:,0]    # MUL ambient[0]  * [{R}]
arr[:,:, 1]  = color[:,:,1] * ambient[:,:,0]    # MUL ambient[0]  * [{G}]
arr[:,:, 2]  = color[:,:,2] * ambient[:,:,0]    # MUL ambient[0]  * [{B}]
arr[:,:,:3] /= 255                              # DIV 255 to normalise
arr[:,:, 3]  = shine[:,:,0]                     # STO shine[  0] in [3]
usec_Vector  = aStopWatch.stop()                # |||||||||||||__.stop
print 'Converting Color Map to image'
print '           Vectorised processing took ', usec_Vector, ' [usec]'
return Image.fromarray( arr.astype( np.uint8 ) )

相关问题 更多 >

    热门问题