danforthcenter / plantcv

Plant phenotyping with image analysis
Mozilla Public License 2.0
662 stars 265 forks source link

Add crop function #496

Closed nfahlgren closed 4 years ago

nfahlgren commented 4 years ago

Is your feature request related to a problem? Please describe. Images are stored as NumPy arrays, which makes extracting a 3D slice easy but requires a little bit of syntax know-how. I think we could provide a crop function that makes this a bit easier and provides some visualization.

Describe the solution you'd like I am picturing a function that looks like pcv.roi.rectangle in terms of inputs that slices an image in the x and y dimensions and returns the extracted section. The function in debug = "plot" or "print" mode would draw a rectangle on the input image to show where the cropping boundaries are. Pseudocode would look like this:

def crop(img, x, y, h, w):
    cropped = img[y:y+h,x:x+w,:]
    # Create the rectangle contour vertices
    pt1 = [x, y]
    pt2 = [x, y + h - 1]
    pt3 = [x + w - 1, y + h - 1]
    pt4 = [x + w - 1, y]

    # Create the ROI contour
    roi_contour = [np.array([[pt1], [pt2], [pt3], [pt4]], dtype=np.int32)]
    # Draw the ROI if requested
    if params.debug is not None:
        # private function in the roi subpackage
        _draw_roi(img=img, roi_contour=roi_contour)
    return cropped

Describe alternatives you've considered Users could readily do this now, the functional part is the first line of code in the function above, but our function might be a bit easier to use.

dschneiderch commented 4 years ago

it would be pythonic to provide an "axis" argument so you can slice in any dimension

nfahlgren commented 4 years ago

Hi @dschneiderch, we were thinking of this as a function that would do a typical "crop" like you would find in an image editor, with a box in the x and y dimensions. The great thing about images an NumPy arrays is that slices can be done in any dimension, this function just does the x and y slicing for the user. @HaleySchuhl made a separate function for the hyperspectral subpackage that extracts arrays in the z (spectral) dimension. Think there's a need for other types of slicing?

dschneiderch commented 4 years ago

As you have it sounds good to me.