使用PIL和numpy进行慢速python图像处理
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用PIL和numpy进行慢速python图像处理,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1954字,纯文字阅读大概需要3分钟。
内容图文
![使用PIL和numpy进行慢速python图像处理](/upload/InfoBanner/zyjiaocheng/815/a84e2b5b3656453dbb5783d4d29571e0.jpg)
我正在尝试使用PIL和Numpy在Python中实现一些图像处理(找到相似颜色的区域).无法弄清楚如何加速这段代码.你能帮忙吗?
def findRegions(self, data):
#data is numpy.array
ret = [[False for _ in range(self.width)] for _ in range(self.heigth)]
for i in range(self.heigth):
for j in range(self.width):
k = 0
acc = 0
for x,y in [(-1,0),(0,-1),(0,1),(1,0)]:
if (self.heigth>i+x>=0 and self.width>j+y>=0):
k = k+1
acc += math.sqrt(sum((data[i][j][c]-data[i+x][j+y][c])**2 for c in range(3)))
if (acc/k<self.threshold):
ret[i][j]= True
return ret
PIL和其他图像库有很多过滤和处理功能,非常快.但是,实现自己的图像处理功能的最佳方法是什么?
解决方法:
您可以将数组向左,向右,向上和向下移动适当数量的元素,而不是在每个行和列上循环.在每个班次中,您将在基础数组中累积值.在移动和累积之后,您计算平均值并应用阈值以返回掩码.请参阅此post,其中有关于该主题的一般性讨论.这个想法是利用numpy的广播,它将一个函数或运算符应用于C中的所有元素而不是Python.
我已经调整了链接帖子中的代码以适应我认为你想要完成的任务.在任何情况下,一般模式都应该加快速度.您必须弄清楚如何处理返回掩码中的边缘.这里我只是将返回掩码设置为False,但您也可以通过在每个方向上将输入数据扩展一个像素并填充最近的像素,零,灰色等来消除边缘.
def findRegions(self,data):
#define the shifts for the kernel window
shifts = [(-1,0),(0,-1),(0,1),(1,0)]
#make the base array of zeros
# array size by 2 in both dimensions
acc = numpy.zeros(data.shape[:2])
#compute the square root of the sum of squared color
# differences between a pixel and it's
# four cardinal neighbors
for dx,dy in shifts:
xstop = -1+dx or None
ystop = -1+dy or None
#per @Bago's comment, use the sum method to add up the color dimension
# instead of the list comprehension
acc += ((data[1:-1,1:-1] - data[1+dx:xstop, 1+dy:ystop])**2).sum(-1)**.5
#compute the average
acc /= (len(shifts) + 1)
#build a mask array the same size as the original
ret = numpy.zeros(data.shape[:2],dtype=numpy.bool)
#apply the threshold
# note that the edges will be False
ret[1:-1,1:-1] acc < self.threshold
return ret
内容总结
以上是互联网集市为您收集整理的使用PIL和numpy进行慢速python图像处理全部内容,希望文章能够帮你解决使用PIL和numpy进行慢速python图像处理所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。