I have a 2D array containing grayscale image created from .png
as follows:
import cv2
img = cv2.imread("./images/test.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
What I would like to do is to extract a subarray containing only the rectangle containing the data - ignoring all zeros surrounding the picture.
For example, if input is:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 175 0 0 0 71 0
0 0 0 12 8 54 0 0
0 0 0 0 255 0 0 0
0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
then output should be:
175 0 0 0 71
0 12 8 54 0
0 0 255 0 0
0 2 0 0 0
I could iterate over the rows in forward direction to find the first nonzero row and then iterate over the rows backwards to find the last nonzero row remembering indices - and then repeat the same for the columns and then extract a subarray using that data but I am sure there are more appropriate ways of doing the same or there even might be a NumPy function designed for such a purpose.
If I were to choose between shortest code vs fastest execution I'd be more interested in fastest code execution.
EDIT:
I did not include the best example because there could be zero rows/columns in the middle as here:
Input:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 175 0 0 0 71 0
0 0 0 12 8 54 0 0
0 0 0 0 255 0 0 0
0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0
Output:
175 0 0 0 71
0 12 8 54 0
0 0 255 0 0
0 0 0 0 0
0 2 0 0 0