python - Elegantly iterate the planes of an image - if more than one -


i come matlab world , i'm relatively new python, think might approaching wrong perspective.

anyway, find myself write code needs operate separately on r,g,b planes of image, needs general enough if image in greyscale still work. non-so-clever way started off is:

if im_in.ndim == 2:   im_out = signal.convolve2d(im_in, filt, 'same') else:   im_out = np.empty_like(im_in)   kk in range(im_in.shape[2]):     im_out[:,:,kk] = signal.convolve2d(im_in, filt, 'same') 

never mind actual operation - i'm using signal.convolve2d example here. , let's assume ndim can 2 or 3 here, simplicity.

now matlab quite clever loop on third dimension of 3d array representing image regardless of number of planes.

the obvious alternative above like:

if im_in.ndim == 2:   im_in.shape = (im_in.shape[0], im_in.shape[1], 1) 

then can loop in third dimension (just in else case above), still seems me bit of hack, , i'd have reshape im_out before end. there proper, elegant way deal case?

you can use numpy.atleast_3d() unconditionally view of input array right number of dimensions, , iterate on planes. has advantage of saving if statement , not modifying input image.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -