Numpy: Get rectangle area just the size of mask
<p><strong>I have an image and a mask. Both are numpy array.</strong> I get the mask through GraphSegmentation (cv2.ximgproc.segmentation), so the area isn't rectangle, but not divided. I'd like to get a rectangle just the size of masked area, but I don't know the efficient way.</p>

<blockquote>
  <p>In other words, unmasked pixels are value of 0 and masked pixels are value over 0, so I want to get a rectangle where...</p>
</blockquote>

<ul>
<li><strong>top</strong> = the smallest index of axis 0 whose value > 0</li>
<li><strong>bottom</strong> = the largest index of axis 0 whose value > 0</li>
<li><strong>left</strong> = the smallest index axis 1 whose value > 0</li>
<li><strong>right</strong> = the largest index axis 1 whose value > 0</li>
<li><strong>image</strong> = src[top : bottom, left : right]</li>
</ul>

<p><strong>My code is below</strong></p>

<pre><code>segmentation = cv2.ximgproc.segmentation.createGraphSegmentation()
src = cv2.imread('image_file')
segment = segmentation.processImage(src)
for i in range(np.max(segment)):
    dst = np.array(src)
    dst[segment != i] = 0
    cv2.imwrite('output_file', dst)
</code></pre>