I am trying to extract the subsection area of an image based on the border of a colored box on the image (see below).
I want to extract the area of the image within the yellow box..
For reference, I am extracting this image from a PDF using pdfplumber's im.draw_rect function, which requires ImageMagick and Ghostscript. I have looked everywhere I can for a solution to this problem, and while Mark Setchell's answer to the question Python: How to cut out an area with specific color from image (OpenCV, Numpy) has come close, I'm getting some unexpected errors.
Here is what I have tried so far:
import numpy as np
from PIL import Image, ImageFilter
impath = r'Path\to\drawn_p9_image.png'
im = Image.open(impath).convert('RGB')
na = np.array(im)
orig= na.copy()
im = im.filter(ImageFilter.MedianFilter(3))
yellowY, yellowX = np.where(np.all(na==[247,213,83],axis=2))
top, bottom = yellowY[0], yellowY[-1]
But when I run the last line, I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 0 is out of bounds for axis 0 with size 0
So the NumPy array is not actually capturing the data it is supposed to. When I checked the NumPy array, this is what it output:
>>> na
array([[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
...,
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8)
I am not sure why this approach is not working, and am looking for some guidance on how to fix it. I am fine with the yellow boundary being visible in the final cropped image, if that provides an easier solution.
