# Crop

import os
import cv2
import numpy as np
from plantcv.plantcv import plot_image
from plantcv.plantcv import print_image
from plantcv.plantcv import params



def crop(img, x, y, h, w):
    """Crop image.

       Inputs:
       img       = RGB, grayscale, or hyperspectral image data
       x         = X coordinate of starting point
       y         = Y coordinate of starting point
       h         = Height
       w         = Width

       Returns:
       cropped   = cropped image

       :param img: numpy.ndarray
       :param x: int
       :param y: int
       :param h: int
       :param w: int
       :return cropped: numpy.ndarray
       """
    params.device += 1

    # Check if the array data format
    if len(np.shape(img)) > 2 and np.shape(img)[-1] > 3:
        cropped = img[y:y + h, x:x + 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)

    ref_img = cv2.rectangle(img=np.copy(img), pt1=pt1, pt2=pt3, color=(255, 0, 0), thickness=params.line_thickness)

    if params.debug == "print":
        # If debug is print, save the image to a file
        print_image(ref_img, os.path.join(params.debug_outdir, str(params.device) + "_crop.png"))
    elif params.debug == "plot":
        # If debug is plot, print to the plotting device
        plot_image(ref_img)

    return cropped

@@ -773,24 +773,198 @@
  3:%0A        
+ref_img = img%5B:, :, %5B0%5D%5D%0A        ref_img = np.transpose(np.transpose(ref_img)%5B0%5D)%0A        cropped = img%5By:y + h, x:x + w, :%5D%0A    else:%0A        ref_img = np.copy(img)%0A        
 cropped = im
@@ -985,17 +985,16 @@
  + w, :%5D
-%0A
 %0A%0A    cr
@@ -1104,66 +1104,8 @@
 = (x
-, y + h - 1)%0A    pt3 = (x + w - 1, y + h - 1)%0A    pt4 = (x
  + w
@@ -1111,16 +1111,24 @@
 w - 1, y
+ + h - 1
 )%0A%0A    r
@@ -1154,28 +1154,23 @@
 gle(img=
-np.copy(
+ref_
 img
-)
 , pt1=pt
@@ -1178,17 +1178,17 @@
 , pt2=pt
-3
+2
 , color=

remove extra contour vertices