简体   繁体   中英

Numpy Manipulation for Image Processing

I've created a script to shift the hue of an image around the colour wheel by any number of steps.

As you might imagine, when I import an image (using PIL) and convert it to a Numpy array, it is this shape: (x, y, (r,g,b)).

I convert this array from RGB to HSV colour space with the Skimage color module (after scaling the RGB values to the range [0,1.0]).

The trouble I am having is manipulation of only one of the HSV values (either H, S, or V) for all pixels. I'd like to efficiently add, multiply, or subtract any of these three dimensions for every 'pixel' in the array.

I have gotten it to work by splitting the HSV values into three separate arrays: h,s,v = np.dsplit(hsv,3)

manipulating the array in the way I want: h_new = np.multiply(h,.33)

and then reassembling the array: hsv_new = np.stack((h_new,s,v))

This doesn't seem like the most efficient way to do this and so my question is: How can I manipulate each of these dimensions without having to split the array into chunks?

hsv[:,:,0] *= 0.33

modifies the h component of hsv inplace.

hsv[:,:,0] is a "basic slice" of hsv and as such, is a view of the original array.


h, s, v = np.dsplit(hsv, 3)

creates 3 new arrays, h , s , v which copy data from hsv . Modifying h , s , v does not affect hsv . So modifying h then requires rebuilding hsv . This is therefore slower.


For notational convenience, you could replace

h,s,v = np.dsplit(hsv, 3)

with

h, s, v = hsv[:,:,0], hsv[:,:,1], hsv[:,:,2]

Then h , s , v will be views of hsv , and modifying h , s , v will automatically affect hsv itself. (So there is no need for hsv_new = np.stack((h_new,s,v)) ).


Note also that h,s,v = np.dsplit(hsv, 3) makes h , s and v have shape (n, m, 1) . Whereas

h, s, v = hsv[:,:,0], hsv[:,:,1], hsv[:,:,2]

makes h , s and v have shape (n, m) . That might affect your other code a little bit, but overall I think the latter is nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM