I have a 2D numpy array iarr
coming from a single color of a picture.
I want to find the minimum/maximum row index in each column with a nonzero value. If there are no nonzero values in a column this column doesn't need to be considered. I have a working solution but it is very slow. My current solution is this
img = Image.open('nameofimage.jpg')
iarr = numpy.array(img)[:,:,0]
nonz = numpy.nonzero(iarr)
colinds = numpy.unique(nonz[1])
minrowinds = numpy.array([numpy.min(nonz[0][nonz[1]==cind]) for cind in colinds])
Thanks to yatu's pointer, I can now answer this myself.
colinds = numpy.unique(nonz[1])
minrowinds = numpy.argmax((iarr>0),axis=0)[colinds]
For the maximum indices I had to flip the array first, as np.argmax
always gives the first occurrence of the maximum value.
maxrowinds = numpy.argmax(numpy.flip((iarr>0),0),axis=0)[colinds]
maxrowinds = iarr.shape[0] - maxrowinds
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.