pythonpython-3.ximage-processingcode-translationidl-programming-language

checking if a value is greater than another and if not replacing with the smaller value idl to python


Hi so I am working on switching over some code from IDL to python and there's this one function shown here:

for i=0l,dim[0]-1 do begin
     for j=0l,dim[1]-1 do begin
        y = reform(image[i,j,0:nchannels-1]) > 0

This makes essentially a list with all the pixel values contained in each channel. Reform takes out the degenerate dimensions so you just have one list of the values from each channel. Then, in idl, the > symbol is different from writing GT. If the symbol is used it says to check if a value in the list is greater than 0 and if not then to just put a 0 there.

I know I could write a loop to be able to do this but I'm wondering if anyone has any nifty python tricks to do this in one line.

Thanks!


Solution

  • I think what you are looking for is numpy.clip().

    import numpy as np
    a = np.array([-3,5,9,1,-7,8,-8,-8,1,3,9])
    a.clip(0)
    # returns: array([0, 5, 9, 1, 0, 8, 0, 0, 1, 3, 9])
    

    It also works with your 3D arrays.