有效地计算图像python的方差 [英] Calculating variance of an image python efficiently
问题描述
我正在开展一个需要获得图像差异的项目。
目前我正采取两种方法(两种方法都有效但速度很慢):
- 单独计算每个像素的方差:
这是使用numpy的代码,varianceMatrix是输出
varianceMatrix = np.zeros(im.shape,np.uint8)
w = 1#像素的半径邻居
ny = len(im)
nx = len(im [0])
for i in range(w,nx-w):
for j in range(w,ny-w):
sampleframe = im [jw:j + w,iw:i + w]
variance = np.var(sampleframe)
varianceMatrix [j] [i] = int(variance)
返回varianceMatrix
- 使用现有的scipy函数:
这是scipy函数:
<$ p $ sc>
来自scipy import ndimage
varianceMatrix = ndimage.generic_filter(im,np.var,size = 3)
scipy函数更快,但不是那么多。我正在寻找一个更好的替代方案来计算方差。
任何想法???
这是一个使用OpenCV的快速解决方案:
import cv2
def winVar(img,wlen):
wmean,wsqrmean =(cv2.boxFilter(x,-1,(wlen,wlen),
borderType = cv2.BORDER_REFLECT)for x in(img,img * img ))
返回wsqrmean - wmean * wmean
在我的机器上和以下示例中, winVar()
比 ndimage.generic_filter()
快2915倍,比快10.8倍sliding_img_var()
(参见pv。的答案):
在[66]中:img = np.random.randint(0,256,(500,500))。astype(np.float)
在[67]中:%timeit winVar(img,3)
100循环,最好3:每循环1.76毫秒
在[68]中:%timeit ndimage.generic_filter(img,np.var,size = 3)
1循环,最佳3:5.13 s /循环
在[69]中:%timeit sliding_img_ var(img,1)
100循环,最佳3:19 ms每循环
结果匹配 ndimage.generic_filter()
:
在[70 ]:np.allclose(winVar(img,3),ndimage.generic_filter(img,np.var,size = 3))
Out [70]:True
I'm working on a project in which need to get the variance of an image. Currently I'm taking 2 approaches (both work but are very slow):
- Calculating the variance for each pixel individually:
This is the code using numpy, varianceMatrix is the output
varianceMatrix = np.zeros(im.shape,np.uint8)
w = 1 # the radius of pixels neighbors
ny = len(im)
nx = len(im[0])
for i in range(w,nx-w):
for j in range(w,ny-w):
sampleframe = im[j-w:j+w, i-w:i+w]
variance = np.var(sampleframe)
varianceMatrix[j][i] = int(variance)
return varianceMatrix
- Using an existing scipy function:
This is the scipy function:
from scipy import ndimage
varianceMatrix = ndimage.generic_filter(im, np.var, size = 3)
The scipy function is faster, but not so much. I'm looking for a better alternative to calculate the variance.
Any ideas???
Here a fast solution using OpenCV:
import cv2
def winVar(img, wlen):
wmean, wsqrmean = (cv2.boxFilter(x, -1, (wlen, wlen),
borderType=cv2.BORDER_REFLECT) for x in (img, img*img))
return wsqrmean - wmean*wmean
On my machine and for the following example, winVar()
is 2915 times faster than ndimage.generic_filter()
and 10.8 times faster than sliding_img_var()
(see pv.'s answer):
In [66]: img = np.random.randint(0, 256, (500,500)).astype(np.float)
In [67]: %timeit winVar(img, 3)
100 loops, best of 3: 1.76 ms per loop
In [68]: %timeit ndimage.generic_filter(img, np.var, size=3)
1 loops, best of 3: 5.13 s per loop
In [69]: %timeit sliding_img_var(img, 1)
100 loops, best of 3: 19 ms per loop
Result matches that of ndimage.generic_filter()
:
In [70]: np.allclose(winVar(img, 3), ndimage.generic_filter(img, np.var, size=3))
Out[70]: True
这篇关于有效地计算图像python的方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!