[Numpy-discussion] Optimizing speed for large-array inter-element algorithms (specifically, color space conversion)
theodore test
tteststudent at gmail.com
Mon Jan 21 09:39:21 EST 2008
Hello all,
I'm scratching my head over how to make this image color space conversion
from "RGB" to "HSV" quicker. It requires input from all three bands of a
given pixel at each pixel, and thus can't be easily flattened. I've already
implemented psyco and removed the extra step of calling colorsys's
rgb_to_hsv function by adapting the code into my primary for loop.
Right now it takes around 9 seconds for a single 1600x1200 RGB image, a
conversion that I've seen implemented more or less instantly in, say,
ImageJ. What can I do to make this conversion more efficient?
Thank you in advance,
Theodore Test
------------
#Necessary imports and hand-waving at psyco usage.
import numpy
from numpy import *
from scipy.misc import pilutil
import psyco
psyco.full()
# Read image file, cram it into a normalized array with one row per pixel
# with each column holding the given pixel's R,G, or B band-value.
s = pilutil.imread('A_Biggish_Image.tif')
r,c,d = s.shape
l = r*c
t = t.reshape(l,3)
t = t/255.0
# Cycle through all of the pixels, converting them to HSV space and putting
them
# back into the array. This is the big time-waster.
#
# The conversion is adapted directly from colorsys.rgb_to_hsv to reduce call
time
for x in range(0,l):
tr = float(t[x,0])
tg = float(t[x,1])
tb = float(t[x,2])
maxc = max(tr, tg, tb)
minc = min(tr, tg, tb)
v = maxc
if minc == maxc:
t[x,0],t[x,1],t[x,2] = 0.0, 0.0, v
else:
s = (maxc-minc) / maxc
rc = (maxc-tr) / (maxc-minc)
gc = (maxc-tg) / (maxc-minc)
bc = (maxc-tb) / (maxc-minc)
if tr == maxc: h = bc-gc
elif tg == maxc: h = 2.0+rc-bc
else: h = 4.0+gc-rc
h = (h/6.0) % 1.0
t[x,0],t[x,1],t[x,2] = h, s, v
# Renormalize shape and contents to image-file standards.
t = t*255.0
t = t.astype(uint8)
t = t.reshape(r,c,d)
finaloutputarray = t
--------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20080121/0d95e77d/attachment.html>
More information about the NumPy-Discussion
mailing list