Issue
I have a black and white image of a triangle (it contains only 0 and 255 pixel values).
I've converted it to a numpy array called myArray
Currently, I can find the width
of the bottom of the triangle (the number of black pixels) by using this code:
width = (max(numpy.where(myArray == 0)[1])) - (min(numpy.where(myArray == 0)[1]))
If the triangle was flipped upside-down, width
would then apply to the top of the upside-down triangle.
What i'm trying to do is determine if the triangle is pointing up or down.
I could do this by finding the first row that contains a black pixel, and counting the number of black pixels in that row, calling this firstRow
and finding the last row that contains a black pixel, and counting the number of black pixels in that row, calling that lastRow
Then, if firstRow
<
lastRow
, the triangle is pointing up.
What is the best way to calculate firstRow
and lastRow
?
Solution
With myArray
with 255 for black pixel such as
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 255., 0., 0., 0., 0.],
[ 0., 0., 0., 255., 255., 255., 0., 0., 0.],
[ 0., 0., 255., 255., 255., 255., 255., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
you can get all the rows with at least one black pixel with np.where
after using sum
on axis=1
:
print (np.where(myArray.sum(axis=1)))
(array([3, 4, 5], dtype=int64),)
If you want to get the row with the maximum number of black pixels, you can use np.argmax
still after sum
on axis=1
:
print (np.argmax(myArray.sum(axis=1)))
5
To know if the triangle is up or down, one way is to check if the argmax
is the np.max
element in the np.where(myArray.sum(axis=1))
, then it would be up.
myArray_sum = myArray.sum(axis=1)
if np.max(np.where(myArray_sum)) == np.argmax(myArray_sum):
print ('up')
else:
print ('down')
If you want the first and last row, here is one way but it is related to the value of the black pixel.
myArray_sum = myArray.sum(axis=1)
firstRow = np.argmax(myArray_sum == 255)
lastRow = np.argmax(myArray_sum)
Answered By - Ben.T
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.