Python - 快速批量修改PNG

2024-01-06

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

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))

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


矢量化代码示例——测试对您的效果timeit or zmq.Stopwatch()

据报道有 22.14 秒 >> 0.1624 秒加速!

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

并使用测试/优化/重新测试循环来加速。

为了测试,使用标准 pythontimeit if [msec]分辨率就够了。

宁愿去zmq.StopWatch()如果你需要进入[usec]解决。

# 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,猜想会更快MUL首先由ambient[:,:,0]最后DIV正常化arr[:,:,:3] /= 255

# test if this goes even faster once saving the vectorised overhead on matrix DIV
arr[:,:,0] = color[:,:,0] * ambient[:,:,0] / 255  # MUL remains INT, shall precede DIV
arr[:,:,1] = color[:,:,1] * ambient[:,:,0] / 255  # 
arr[:,:,2] = color[:,:,2] * ambient[:,:,0] / 255  # 
arr[:,:,3] = shine[:,:,0]                         # STO alpha

那么它在你的算法中看起来怎么样?

人们不需要彼得·杰克逊令人印象深刻的预算和时间曾经在新西兰的一个机库里计划、跨越并执行了三年多的大量数字运算,当时他正在制作“指环王“全数字母带制作流水线,通过逐帧像素操作,认识到毫秒、微秒甚至纳秒在大规模生产流程中确实很重要。

因此,深呼吸并进行测试和重新测试,以便将现实世界的图像处理性能优化到项目所需的水平。

希望这可以帮助您:

# 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 ) )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - 快速批量修改PNG 的相关文章

  • 为什么 Python 在导入脚本时只保存脚本的字节码?

    既然执行Python字节码会比运行原始源代码更快 因为Python不需要重新编译 为什么Python在导入脚本时只保存编译后的字节码呢 为每个执行的脚本保存 pyc 文件不是更好吗 无论如何 Python 解释器的启动时间都需要时间 即使您
  • 如何在 Debian 上的 virtualenv 中安装 numpy?

    注 参见这另一篇文章 https stackoverflow com questions 6442754 how to install h5py numpylibhdf5 as non root on a debian linux syst
  • 在Python中,如何将矩阵逆时针旋转90度?

    gt gt gt def rotate matrix k List List int For example if I have m 1 2 3 2 3 3 5 4 3 rotate matrix m should give me 3 3
  • 键入的完整命令行

    我想获得输入时的完整命令行 This join sys argv 在这里不起作用 删除双引号 另外 我不想重新加入已解析和拆分的内容 有任何想法吗 你太迟了 当键入的命令到达 Python 时 您的 shell 已经发挥了它的魔力 例如 引
  • Matplotlib 图例,跨列添加项目而不是向下添加项目

    对于下面的简单绘图 有没有办法让 matplotlib 填充图例 以便它从左到右填充行 而不是第一列然后第二列 gt gt gt from pylab import gt gt gt x arange 2 pi 2 pi 0 1 gt gt
  • 为什么在连接两个字符串时 Python 比 C 更快?

    目前我想比较 Python 和 C 用来处理字符串的速度 我认为 C 应该比 Python 提供更好的性能 然而 我得到了完全相反的结果 这是 C 程序 include
  • 雅虎财务请求功能出现 404 客户端错误

    yahoo Financials的请求功能出现404 Client Error 直接点击以下网址没有问题 https finance yahoo com quote AAPL financials p AAPL https finance
  • 在linux上安装python ssl模块,无需重新编译

    是否可以在已经安装了 OpenSSL 的 Linux 机器上安装 python 的 SSL 模块 而无需重新编译 python 我希望它就像复制几个文件并将它们包含在库路径中一样简单 Python版本是2 4 3 谢谢 是否可以在已经安装了
  • 在请求中设置端口

    我正在尝试利用cgminer使用 Python 的 API 我对利用requests图书馆 我了解如何做基本的事情requests but cgminer想要更具体一点 我想缩小 import socket import json sock
  • 数据框中 .map(str) 和 .astype(str) 有什么区别

    我有一个数据框 其列名为 col1 和 col2 的整数类型条目 我想将 col1 和 col2 的条目以及其间的 点 连接起来 我搜索并发现添加两个列条目 df col df col1 map str df col2 map str 并添
  • 类型错误:此 COM 对象无法自动执行 makepy 过程 - 请为此对象手动运行 makepy

    这是什么错误 回溯错误 C Users DELL PycharmProjects MyNew venv Scripts python exe C Users DELL PycharmProjects MyNew agaaaaain py T
  • 更改 Matplotlib 投影轴的背景颜色

    我正在尝试使用 Cartopy 创建一个图形 该图形需要在未投影的轴上绘制投影轴 这是一个尽可能简单的代码版本 它将轴上的内容替换为背景颜色 import matplotlib pyplot as plt import cartopy cr
  • 使用 if 语句的网格网格和用户定义函数的真值不明确

    假设我有一个函数f x y 足够光滑 然而 有些值仅在有限的意义上存在 以sin x x的价值x 0只存在于极限 x gt 0 中 在一般情况下 我用一个来处理这个问题if陈述 如果我在情节中使用它meshgrid我收到一条错误消息 Val
  • 在 Matlab 中保存 Kinect 深度图像?

    通过使用 Kinect 我可以获得深度图像 其中每个深度图像像素存储相机和物体之间的距离 以毫米为单位 现在我想保存它们以便以后使用 最好的推荐是什么 我正在考虑将深度图像保存为图像 jpg png等 然而 该值通常是从50毫米到10000
  • 为什么 Collections.counter 这么慢?

    我正在尝试解决罗莎琳德的基本问题 即计算给定序列中的核苷酸 并在列表中返回结果 对于那些不熟悉生物信息学的人来说 它只是计算字符串中 4 个不同字符 A C G T 出现的次数 我期望collections Counter是最快的方法 首先
  • jpegtran 优化而不更改文件名

    我需要优化一些图像 但不更改它们的名称 jpegtran copy none optimize image jpg gt image jpg 但是 这似乎创建了 0 的文件大小 当我对不同的文件名执行此操作时 大小仍然完全相同 怎么样 jp
  • Python 相当于 Scala 案例类

    Python 中是否有与 Scala 的 Case Class 等效的东西 就像自动生成分配给字段而无需编写样板的构造函数一样 当前执行此操作的现代方法 从 Python 3 7 开始 是使用数据类 https www python org
  • 使用 MPI 的 Allreduce 对 Python 对象求和

    我正在使用使用 Python 中的字典和计数器构建的稀疏张量数组操作 我想让并行使用这个数组操作成为可能 最重要的是 我最终在每个节点上都有计数器 我想使用 MPI Allreduce 或另一个不错的解决方案 将其添加在一起 例如 使用计数
  • 为boost python编译的.so找不到模块

    我正在尝试将 C 代码包装到 python 中 只需一个类即可导出两个函数 我编译为map so 当我尝试时import map得到像噪音一样的错误 Traceback most recent call last File
  • 如何使用 Python/Django 在 Facebook 中获取(和使用)扩展权限

    我正在尝试编写一个简单的应用程序 让用户授予我的代码写入其页面的 Facebook 流的权限 据我了解 它应该很简单 让用户单击一个按钮 启动一个弹出窗口 其中包含我的 Facebook 应用程序中的页面 在该页面中 他们单击授予的内容流发

随机推荐