+def ftrim(Mat):
+ # private func to trim the Matrix, but in one direction, vertically | horizontally
+ # return the slice, don't affect the Matrix
+ # y | : for column, x -> : for rows
+ # v
+ # not my fault, numpy architecture
+ y1 = y2 = i = 0
+ while i < len(Mat):# search by top
+ if max(Mat[i]) > 0:
+ y1 = i
+ break
+ i += 1
+ i = len(Mat) - 1
+ while i >= 0:# search by bottom
+ if max(Mat[i]) > 0:
+ y2 = i
+ break
+ i -= 1
+ # print('y1, y2', y1, y2)
+ return slice(y1, y2+1)# +1 to stop at y2
+
+def trim(Mat):
+ # most use who make implicit call of ftrim twice
+ horizontal = ftrim(Mat)
+ vertical = ftrim(Mat.T)
+ # print('horizontal:vertical', horizontal, vertical)
+ return Mat[horizontal, vertical]
+