[Numpy-discussion] efficient 3d histogram creation

Chris Colbert sccolbert at gmail.com
Mon May 4 00:31:40 EDT 2009


this actually sort of worked. Thanks for putting me on the right track.

Here is what I ended up with.

 this is what I ended up with:

def hist3d(imgarray):
    histarray = N.zeros((16, 16, 16))
    temp = imgarray.copy()
    bins = N.arange(0, 257, 16)
    histarray = N.histogramdd((temp[:,:,0].ravel(), temp[:,:,1].ravel(),
temp[:,:,2].ravel()), bins=(bins, bins, bins))[0]
    return histarray

this creates a 3d histogram of rgb image values in the range 0,255 using 16
bins per component color.

on a 640x480 image, it executes in 0.3 seconds vs 4.5 seconds for a for
loop.

not quite framerate, but good enough for prototyping.

Thanks!

Chris

On Sun, May 3, 2009 at 8:36 PM, <josef.pktd at gmail.com> wrote:

>  On Sun, May 3, 2009 at 8:15 PM, Chris Colbert <sccolbert at gmail.com>
> wrote:
> > in my endless pursuit of perfomance, i'm searching for a quick way to
> create
> > a 3d histogram from a 3d rgb image.
> >
> > Here is what I have so far for a (16,16,16) 3d histogram:
> >
> > def hist3d(imgarray):
> >     histarray = N.zeros((16, 16, 16))
> >     temp = imgarray.copy()
> >     (i, j) = imgarray.shape[0:2]
> >     temp = (temp - temp % 16) / 16
> >     for a in range(i):
> >         for b in range(j):
> >             (b1, b2, b3) = temp[a, b, :]
> >             histarray[b1, b2, b3] += 1
> >     return histarray
> >
> > this works, but takes about 4 seconds for a 640x480 image.
> >
> > I tried doing the inverse of my previous post, namely replacing the
> nested
> > for loop with:
> > histarray[temp[:,:,0], temp[:,:,1], temp[:,:,2]] += 1
> >
> >
> > but that doesn't work for whatever reason. It gives me number, but
> they're
> > incorrect.
> >
> > Any ideas?
>
> I'm not sure what exactly you need, but did you look at np.histogramdd ?
>
> reading the help file, this might work
>
> numpy.histogramdd(temp[:,:,0].ravel(), temp[:,:,1].ravel(),
> temp[:,:,2].ravel(), bins=16)
>
> but I never used histogramdd.
>
> also looking at the source of numpy is often very instructive, lots of
> good tricks to find in there: np.source(np.histogramdd).
>
> Josef
>  _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090504/691b632c/attachment.html>


More information about the NumPy-Discussion mailing list