numpy/线性代数-快速16位直方图 [英] numpy / linear algebra - fast 16-bit histogram
问题描述
如果我有一个由uint16s组成的图像,并且想要为每个位计算一个直方图,即包含强度值的 0..65535
的矢量'x'和一个矢量 y
是具有该值的样本数,是否有矢量化的numpy/线性algreba方法来计算?
If I have an image made of uint16s and want to compute a histogram for each bit, i.e. a vector 'x' of 0..65535
that contains the intensity value, and a vector y
that is the number of samples that have that value, is there a vectorized numpy / linear algreba way to compute this?
推荐答案
我使用Numpy进行了明显的处理,并且在Mac上使用图像尺寸需要300毫秒.然后我用OpenCV做同样的事情,它在9毫秒时快了33倍!
I did it the obvious way with Numpy, and using your image dimensions on my Mac, it takes 300ms. I then did the same thing with OpenCV and it is 33x faster at 9ms!
#!/usr/bin/env python3
import cv2
import numpy as np
# Dimensions - height, width
h, w = 2160, 2560
# Known image, channel0=1, channel1=3, channel2=5, channel3=65535
R = np.zeros((h,w,4), dtype=np.uint16)
R[...,0] = 1
R[...,1] = 3
R[...,2] = 5
R[...,3] = 65535
def npHistogram(R):
"""Generate histogram using Numpy"""
H, _ = np.histogram(R,65536)
return H
def OpenCVHistogram(R):
"""Generate histogram using OpenCV"""
H = cv2.calcHist([R.ravel()], [0], None, [65536], [0,65536])
return H
A = npHistogram(R)
B = OpenCVHistogram(R)
#%timeit npHistogram(R)
#%timeit OpenCVHistogram(R)
结果
使用IPython,我得到了这些计时信息
Using IPython, I got these timings
%timeit npHistogram(R)
300 ms ± 11.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit OpenCVHistogram(R)
9.02 ms ± 226 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
关键字:Python,直方图,慢速,Numpy,np.histogram,加速,OpenCV,图像处理.
Keywords: Python, histogram, slow, Numpy, np.histogram, speedup, OpenCV, image processing.
这篇关于numpy/线性代数-快速16位直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!