Example #1
0
def from_binary_image(bin_img, img):
    """Create an ROI from a binary image

    Inputs:
    bin_img       = Binary image to extract an ROI contour from.
    img           = An RGB or grayscale image to plot the ROI on.

    Outputs:
    roi_contour   = An ROI set of points (contour).
    roi_hierarchy = The hierarchy of ROI contour(s).

    :param bin_img: numpy.ndarray
    :param img: numpy.ndarray
    :return roi_contour: list
    :return roi_hierarchy: numpy.ndarray
    """
    # Autoincrement the device counter
    params.device += 1
    # Make sure the input bin_img is binary
    if len(np.unique(bin_img)) != 2:
        fatal_error("Input image is not binary!")
    # Use the binary image to create an ROI contour
    roi_contour, roi_hierarchy = cv2.findContours(np.copy(bin_img),
                                                  cv2.RETR_TREE,
                                                  cv2.CHAIN_APPROX_NONE)[-2:]
    # Draw the ROI if requested
    if params.debug is not None:
        _draw_roi(img=img, roi_contour=roi_contour)

    return roi_contour, roi_hierarchy
def grab_random(database, random, outdir, imgtype):
    # Does the database exist?
    if not os.path.exists(database):
        pcv.fatal_error("The database file " + str(database) + " does not exist")

    # Open a connection
    try:
        db = sq.connect(database)
    except sq.Error as e:
        print("Error %s:" % e.args[0])
    else:
        if imgtype == "VIS":
            # Get the headers for metadata and headers for features these will be the headers of features table
            metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                           'metadata.image_id=analysis_images.image_id where '
                                           'analysis_images.type=="mask" and metadata.imgtype=="VIS"', db)
        elif imgtype == "NIR":
            # Get the headers for metadata and headers for features these will be the headers of features table
            metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                           'metadata.image_id=analysis_images.image_id where '
                                           'analysis_images.type=="mask" and metadata.imgtype=="NIR"', db)
        elif imgtype == "None":
            # Get the headers for metadata and headers for features these will be the headers of features table
            metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                           'metadata.image_id=analysis_images.image_id where '
                                           'analysis_images.type=="mask" and metadata.imgtype=="none"', db)
        else:
            pcv.fatal_error("imgtype is not VIS, NIR or None")

        sorted = metaimages.sort_values(['timestamp'])

        nrowsorted = sorted.shape[0]

        chunksfactor = nrowsorted / float(random)

        random_index_list = []

        for i in range(2, random + 1, 1):
            x = int((i - 1) * chunksfactor)
            y = int(i * chunksfactor)
            randnum = randrange(x, y)
            random_index_list.append(randnum)

        maskdir = os.path.join(outdir, "training-mask-images")
        oridir = os.path.join(outdir, "training-ori-images")

        if not os.path.exists(maskdir):
            os.makedirs(maskdir)
        if not os.path.exists(oridir):
            os.makedirs(oridir)

        for x in random_index_list:
            selectmask = str(sorted.iloc[[x - 1]]['image_path'].item())
            selectori = str(sorted.iloc[[x - 1]]['image'].item())
            copy(selectmask, maskdir + "/")
            copy(selectori, oridir + "/")
Example #3
0
def db_lookup(database, ids, outdir, type, vis=False, nir=False, flu=False):
  # Does the database exist?
  if not os.path.exists(database):
    pcv.fatal_error("The database file " + str(database) + " does not exist");
  
  # Open a connection
  try:
    connect=sq.connect(database)
  except sq.Error, e:
    print("Error %s:" % e.args[0])
def db_lookup(database, outdir, type):
  # Does the database exist?
  if not os.path.exists(database):
    pcv.fatal_error("The database file " + str(database) + " does not exist");
  
  # Open a connection
  try:
    connect=sq.connect(database)
  except sq.Error, e:
    print("Error %s:" % e.args[0])
Example #5
0
def grab_random(database,random, outdir, imgtype):
  # Does the database exist?
  if not os.path.exists(database):
    pcv.fatal_error("The database file " + str(database) + " does not exist");
  
  # Open a connection
  try:
    connect=sq.connect(database)
  except sq.Error, e:
    print("Error %s:" % e.args[0])
Example #6
0
def main():
  # Get options
  args = options()
  
  # Does the database exist?
  if not os.path.exists(args.database):
    pcv.fatal_error("The database file " + str(args.database) + " does not exist");
  
  # Open a connection
  try:
    connect=sq.connect(args.database)
  except sq.Error, e:
    print("Error %s:" % e.args[0])
def main():
  # Get options
  args = options()
  
  # Does the database exist?
  if not os.path.exists(args.database):
    pcv.fatal_error("The database file " + str(args.database) + " does not exist");
  
  # Open a connection
  try:
    connect=sq.connect(args.database)
  except sq.Error, e:
    print("Error %s:" % e.args[0])
Example #8
0
def db_lookup(database,
              outdir,
              queries,
              vis=False,
              nir=False,
              psii=False,
              verbose=False):
    # Does the database exist?
    if not os.path.exists(database):
        pcv.fatal_error("The database file " + str(database) +
                        " does not exist")

    # Open a connection
    try:
        connect = sq.connect(database)
    except sq.Error as e:
        IOError("Error %s:" % e.args[0])
    else:
        # Replace the row_factory result constructor with a dictionary constructor
        connect.row_factory = dict_factory
        # Change the text output format from unicode to UTF-8
        connect.text_factory = str

        # Database handler
        db = connect.cursor()

        for query in queries:
            query = 'select * from metadata where ' + str(query)
            if verbose:
                print(query)
            for row in (db.execute(query)):
                dt = datetime.datetime.strptime(
                    row['timestamp'],
                    "%Y-%m-%d %H:%M:%S.%f").strftime('%Y-%m-%d-%H-%M-%S')
                if vis and row['imgtype'] == 'VIS':
                    img_name = os.path.join(
                        outdir, row['plantbarcode'] + "_" + dt + "_" +
                        os.path.basename(row['image']))
                    copy(row['image'], img_name)
                if nir and row['imgtype'] == 'NIR':
                    img_name = os.path.join(
                        outdir, row['plantbarcode'] + "_" + dt + "_" +
                        os.path.basename(row['image']))
                    copy(row['image'], img_name)
                if psii and row['imgtype'] == 'PSII':
                    images = row['image'].split(',')
                    for image in images:
                        img_name = os.path.join(
                            outdir, row['plantbarcode'] + "_" + dt + "_" +
                            os.path.basename(image))
                        copy(image, img_name)
def grab_random(database, random, imgtype, camera, outdir, verbose):
    # Does the database exist?
    if not os.path.exists(database):
        pcv.fatal_error("The database file " + str(database) +
                        " does not exist")

    # Open a connection
    try:
        connect = sq.connect(database)
    except sq.Error as e:
        print("Error %s:" % e.args[0])
    else:
        # Replace the row_factory result constructor with a dictionary constructor
        connect.row_factory = dict_factory
        # Change the text output format from unicode to UTF-8
        connect.text_factory = str

        # Database handler
        db = connect.cursor()
        imageid_list = []
        num = random
        if verbose:
            print(num)
        list_random = db.execute(
            'select * from metadata where imgtype=? and camera=? order by random() limit ?',
            (
                imgtype,
                camera,
                num,
            ))
        for i, x in enumerate(list_random):
            imgid = x['image_id']
            imageid_list.append(imgid)

        if verbose:
            print(imageid_list)

        for imgid in imageid_list:
            get_image = db.execute('select * from metadata where image_id=?',
                                   (imgid, ))
            for row in get_image:
                dt = datetime.datetime.strptime(
                    row['timestamp'],
                    "%Y-%m-%d %H:%M:%S.%f").strftime('%Y-%m-%d-%H-%M-%S')
                img_name = os.path.join(
                    outdir, row['plantbarcode'] + "_" + dt + "_" +
                    os.path.basename(row['image']))
                copy(row['image'], img_name)
                if verbose:
                    print("copying")
                    print(img_name)
Example #10
0
def ellipse(x, y, r1, r2, angle, img):
    """Create an elliptical ROI.

    Inputs:
    x             = The x-coordinate of the center of the ellipse.
    y             = The y-coordinate of the center of the ellipse.
    r1            = The radius of the major axis.
    r2            = The radius of the minor axis.
    angle         = The angle of rotation of the major axis.
    img           = An RGB or grayscale image to plot the ROI on in debug mode.

    Outputs:
    roi_contour   = An ROI set of points (contour).
    roi_hierarchy = The hierarchy of ROI contour(s).

    :param x: int
    :param y: int
    :param r1: int
    :param r2: int
    :param angle: int
    :param img: numpy.ndarray
    :return roi_contour: list
    :return roi_hierarchy: numpy.ndarray
    """
    # Autoincrement the device counter
    params.device += 1

    # Get the height and width of the reference image
    height, width = np.shape(img)[:2]

    # Initialize a binary image of the ellipse
    bin_img = np.zeros((height, width), dtype=np.uint8)
    # Draw the ellipse on the binary image
    cv2.ellipse(bin_img, (x, y), (r1, r2), angle, 0, 360, 255, -1)

    if np.sum(bin_img[0, :]) + np.sum(bin_img[-1, :]) + np.sum(
            bin_img[:, 0]) + np.sum(bin_img[:, -1]) > 0:
        fatal_error("The ROI extends outside of the image!")

    # Use the binary image to create an ROI contour
    roi_contour, roi_hierarchy = cv2.findContours(np.copy(bin_img),
                                                  cv2.RETR_TREE,
                                                  cv2.CHAIN_APPROX_NONE)[-2:]

    # Draw the ROI if requested
    if params.debug is not None:
        _draw_roi(img=img, roi_contour=roi_contour)

    return roi_contour, roi_hierarchy
Example #11
0
def rectangle(x, y, h, w, img):
    """Create a rectangular ROI.

    Inputs:
    x             = The x-coordinate of the upper left corner of the rectangle.
    y             = The y-coordinate of the upper left corner of the rectangle.
    h             = The height of the rectangle.
    w             = The width of the rectangle.
    img           = An RGB or grayscale image to plot the ROI on in debug mode.

    Outputs:
    roi_contour   = An ROI set of points (contour).
    roi_hierarchy = The hierarchy of ROI contour(s).

    :param x: int
    :param y: int
    :param h: int
    :param w: int
    :param img: numpy.ndarray
    :return roi_contour: list
    :return roi_hierarchy: numpy.ndarray
    """
    # Autoincrement the device counter
    params.device += 1

    # Get the height and width of the reference image
    height, width = np.shape(img)[:2]

    # Check whether the ROI is correctly bounded inside the image
    if x < 0 or y < 0 or x + w > width or y + h > height:
        fatal_error("The ROI extends outside of the image!")

    # 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)]
    roi_hierarchy = np.array([[[-1, -1, -1, -1]]], dtype=np.int32)

    # Draw the ROI if requested
    if params.debug is not None:
        _draw_roi(img=img, roi_contour=roi_contour)

    return roi_contour, roi_hierarchy
Example #12
0
def circle(x, y, r, img):
    """Create a circular ROI.

    Inputs:
    x             = The x-coordinate of the center of the circle.
    y             = The y-coordinate of the center of the circle.
    r             = The radius of the circle.
    img           = An RGB or grayscale image to plot the ROI on in debug mode.

    Outputs:
    roi_contour   = An ROI set of points (contour).
    roi_hierarchy = The hierarchy of ROI contour(s).

    :param x: int
    :param y: int
    :param r: int
    :param img: numpy.ndarray
    :return roi_contour: list
    :return roi_hierarchy: numpy.ndarray
    """
    # Autoincrement the device counter
    params.device += 1

    # Get the height and width of the reference image
    height, width = np.shape(img)[:2]

    # Check whether the ROI is correctly bounded inside the image
    if x - r < 0 or x + r > width or y - r < 0 or y + r > height:
        fatal_error("The ROI extends outside of the image!")

    # Initialize a binary image of the circle
    bin_img = np.zeros((height, width), dtype=np.uint8)
    # Draw the circle on the binary image
    cv2.circle(bin_img, (x, y), r, 255, -1)

    # Use the binary image to create an ROI contour
    roi_contour, roi_hierarchy = cv2.findContours(np.copy(bin_img),
                                                  cv2.RETR_TREE,
                                                  cv2.CHAIN_APPROX_NONE)[-2:]

    # Draw the ROI if requested
    if params.debug is not None:
        _draw_roi(img=img, roi_contour=roi_contour)

    return roi_contour, roi_hierarchy
Example #13
0
def handle_vis_output(directory, imgtype, outdir, action):
    # directory = path to directory you want to grab images from
    # imgtype = type of output image you want to move or copy (options are rgb_slice, pseudo_on_img, pseudo_on_white, shapes, or, histogram)
    # outdir = where you want the images to go
    # action = either 'copy' or 'move'

    if imgtype == 'rgb_slice':
        path = str(directory)
        opendir = os.listdir(path)
        for filename in opendir:
            if re.search("rgb_norm_slice\.png$", filename):
                fromDirectory = str(directory) + str(filename)
                toDirectory = str(outdir) + str(filename)
                if action == 'copy':
                    distutils.file_util.copy_file(fromDirectory, toDirectory)
                elif action == 'move':
                    distutils.file_util.move_file(fromDirectory, toDirectory)
                else:
                    pcv.fatal_error('action' +
                                    (str(action) + ' is not move or copy'))
            else:
                pcv.fatal_error("Sorry no " + str(imgtype) + " images found")
    elif imgtype == 'pseudo_on_img':
        path = str(directory)
        opendir = os.listdir(path)
        for filename in opendir:
            if re.search("pseudo_on_img\.png$", filename):
                fromDirectory = str(directory) + str(filename)
                toDirectory = str(outdir) + str(filename)
                if action == 'copy':
                    distutils.file_util.copy_file(fromDirectory, toDirectory)
                elif action == 'move':
                    distutils.file_util.move_file(fromDirectory, toDirectory)
                else:
                    pcv.fatal_error('action' +
                                    (str(action) + ' is not move or copy'))
            else:
                pcv.fatal_error("Sorry no " + str(imgtype) + " images found")
    elif imgtype == 'pseudo_on_white':
        path = str(directory)
        opendir = os.listdir(path)
        for filename in opendir:
            if re.search("pseudo_on_white\.png$", filename):
                fromDirectory = str(directory) + str(filename)
                toDirectory = str(outdir) + str(filename)
                if action == 'copy':
                    distutils.file_util.copy_file(fromDirectory, toDirectory)
                elif action == 'move':
                    distutils.file_util.move_file(fromDirectory, toDirectory)
                else:
                    pcv.fatal_error('action' +
                                    (str(action) + ' is not move or copy'))
            else:
                pcv.fatal_error("Sorry no " + str(imgtype) + " images found")
    elif imgtype == 'shapes':
        path = str(directory)
        opendir = os.listdir(path)
        for filename in opendir:
            if re.search("shapes\.png$", filename):
                fromDirectory = str(directory) + str(filename)
                toDirectory = str(outdir) + str(filename)
                if action == 'copy':
                    distutils.file_util.copy_file(fromDirectory, toDirectory)
                elif action == 'move':
                    distutils.file_util.move_file(fromDirectory, toDirectory)
                else:
                    pcv.fatal_error('action' +
                                    (str(action) + ' is not move or copy'))
            else:
                pcv.fatal_error("Sorry no " + str(imgtype) + " images found")
    elif imgtype == 'histogram':
        path = str(directory)
        opendir = os.listdir(path)
        for filename in opendir:
            if re.search("hist\.png$", filename):
                fromDirectory = str(directory) + str(filename)
                toDirectory = str(outdir) + str(filename)
                if action == 'copy':
                    distutils.file_util.copy_file(fromDirectory, toDirectory)
                elif action == 'move':
                    distutils.file_util.move_file(fromDirectory, toDirectory)
                else:
                    pcv.fatal_error('action' +
                                    (str(action) + ' is not move or copy'))
            else:
                pcv.fatal_error("Sorry no " + str(imgtype) + " images found")
    else:
        pcv.fatal_error('imgtype' + (
            str(imgtype) +
            ' is not rgb_slice, pseudo_on_img, pseudo_on_white, shapes, or, histogram!'
        ))
Example #14
0
def define_multi_roi(img,
                     device,
                     debug=False,
                     roi_file=None,
                     roi_input='default',
                     rows=None,
                     col=None,
                     shape=None,
                     rad=None,
                     dist_x=None,
                     dist_y=None,
                     adjust_x=False,
                     adjust_y=False):
    #If you have very irregularly spaced ROI (that stays consistent between images), it is likely easiest to provide a file with an ROI
    #But remember that the ROIs can capture objects outside of their borders as long as the object is connected (partially inside ROI) so some irregularities are fine

    # img= img to overlay roi
    # roi_file= default is None, else the user can input an ROI image, object area shoud be white and background area should be black.
    # roi_input= type of image that the roi_file is, either 'binary', 'rgb' or 'default' (no ROI inputted)
    # debug= True/False, if True, print image
    # rows= number of rows of rois
    # col= number of columns of rois
    # shape= None, 'circle', or 'square'
    # rad= radius or height/width of shape
    # dist_x= distance between edges on the x axis
    # dist_y= distance between edges on the y axis
    # adjust_x= distance to move set of roi in the x direction
    # adjust_y= distance to move set of roi in the y direction

    device += 1

    ori_img = np.copy(img)
    if len(np.shape(img)) == 3:
        ix, iy, iz = np.shape(img)
    else:
        ix, iy = np.shape(img)

    #Allows user to use the default ROI or input their own RGB or binary image (made with imagej or some other program) as a base ROI (that can be adjusted below if necessary)
    if roi_input == 'rgb':
        hsv = cv2.cvtColor(roi_file, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(hsv)
        ret, v_img = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY)
        roi_contour, roi_hierarchy = cv2.findContours(v_img, cv2.RETR_TREE,
                                                      cv2.CHAIN_APPROX_NONE)
        if debug:
            print_image(roi_file, (str(device) + '_roi.png'))
    elif roi_input == 'binary':
        roi_contour, roi_hierarchy = cv2.findContours(roi_file, cv2.RETR_TREE,
                                                      cv2.CHAIN_APPROX_NONE)
        if debug:
            print_image(roi_file, (str(device) + '_roi.png'))
    elif roi_input == 'default':
        size = ix, iy
        roi_background = np.zeros(size, dtype=np.uint8)
        roi_size = (ix - 5), (iy - 5)
        roi = np.zeros(roi_size, dtype=np.uint8)
        roi1 = roi + 1
        roi_contour, roi_heirarchy = cv2.findContours(roi1, cv2.RETR_TREE,
                                                      cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(roi_background, roi_contour[0], -1, (255, 0, 0), 5)
    else:
        fatal_error('ROI Input' + str(roi_input) +
                    ' is not "binary", "rgb" or "default roi"!')

    print roi_contour
    print v

    ##If the ROI is exactly in the 'correct' position
    #if adjust_x==False and adjust_y==False:
    #  if roi_input=='rgb' or roi_input=='binary':
    #    size = ix,iy,3
    #    background = np.zeros(size, dtype=np.uint8)
    #    roi_contour1=roi_contour+background
    #    roi_heirarchy1=roi_heirarchy
    #    cv2.drawContours(ori_img,roi_contour1[0],-1,(255,0,0),5)
    #    if debug:
    #      print_image(ori_img,(str(device)+'ori_roi.png'))
    #    #return device,roi_contour1,roi_heirarchy1

    #for cnt in roi_contour:
    #  size = ix,iy,3
    #  background = np.zeros(size, dtype=np.uint8)
    #  if shape=='square':
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    cv2.rectangle(background,(x,y),(x+w,y+h),(0,255,0),5)
    #    rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #    rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #    cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
    #    if debug:
    #      print_image(ori_img, (str(device) + '_roi.png'))
    #    return device, rect_contour, hierarchy
    #  elif shape== 'circle':
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    center = (int(w/2),int(h/2))
    #    if h>w:
    #      radius = int(w/2)
    #      cv2.circle(background,center,radius,(255,255,255),-1)
    #      circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, circle_contour, hierarchy
    #    else:
    #      radius = int(h/2)
    #      cv2.circle(background,center,radius,(255,255,255),-1)
    #      circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, circle_contour, hierarchy
    #  elif shape== 'ellipse':
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    center = (int(w/2),int(h/2))
    #    if w>h:
    #      cv2.ellipse(background,center,(w/2,h/2),0,0,360, (0,255,0), 2)
    #      ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, ellipse_contour, hierarchy
    #    else:
    #      cv2.ellipse(ori_img,center,(h/2,w/2),0,0,360, (0,255,0), 2)
    #      cv2.ellipse(background,center,(h/2,w/2),0,0,360, (0,255,0), 2)
    #      ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, ellipse_contour, hierarchy
    #  else:
    #      fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')

    #Adjust ROI moves the inputted or created ROI

    return device


#def define_roi(img, shape, device, roi=None, roi_input='default', debug=False, adjust=False, x_adj=0, y_adj=0, w_adj=0, h_adj=0):
#  # img = img to overlay roi
#  # roi =default (None) or user input ROI image, object area should be white and background should be black, has not been optimized for more than one ROI
#  # roi_input = type of file roi_base is, either 'binary', 'rgb', or 'default' (no ROI inputted)
#  # shape = desired shape of final roi, either 'rectangle' or 'circle', if  user inputs rectangular roi but chooses 'circle' for shape then a circle is fitted around rectangular roi (and vice versa)
#  # device = device number.  Used to count steps in the pipeline
#  # debug = True/False. If True, print image
#  # adjust= either 'True' or 'False', if 'True' allows user to adjust ROI
#  # x_adj = adjust center along x axis
#  # y_adj = adjust center along y axis
#  # w_adj = adjust width
#  # h_adj = adjust height
#
#  device += 1
#  ori_img=np.copy(img)
#  if len(np.shape(img))==3:
#    ix,iy,iz=np.shape(img)
#  else:
#    ix,iy=np.shape(img)
#
#  #Allows user to use the default ROI or input their own RGB or binary image (made with imagej or some other program) as a base ROI (that can be adjusted below)
#  if roi_input== 'rgb':
#    hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
#    h,s,v = cv2.split(hsv)
#    ret,v_img = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY)
#    roi_contour,hierarchy = cv2.findContours(v_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#  elif roi_input== 'binary':
#    roi_contour,hierarchy = cv2.findContours(rois,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#  elif roi_input=='default':
#    size = ix,iy
#    roi_background = np.zeros(size, dtype=np.uint8)
#    roi_size=(ix-5),(iy-5)
#    roi=np.zeros(roi_size, dtype=np.uint8)
#    roi1=roi+1
#    roi_contour,roi_heirarchy=cv2.findContours(roi1,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#    cv2.drawContours(roi_background,roi_contour[0],-1, (255,0,0),5)
#    if adjust==True:
#      if x_adj>0 and w_adj>0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#      elif y_adj>0 and h_adj>0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#      elif x_adj<0 or y_adj<0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#  else:
#    fatal_error('ROI Input' + str(roi_input) + ' is not "binary", "rgb" or "default roi"!')
#
#  #If the ROI is exactly in the 'correct' position
#  if adjust==False:
#    for cnt in roi_contour:
#      size = ix,iy,3
#      background = np.zeros(size, dtype=np.uint8)
#      if shape=='rectangle':
#        x,y,w,h = cv2.boundingRect(cnt)
#        cv2.rectangle(background,(x,y),(x+w,y+h),(0,255,0),5)
#        rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#        rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#        cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
#        if debug:
#          print_image(ori_img, (str(device) + '_roi.png'))
#        return device, rect_contour, hierarchy
#      elif shape== 'circle':
#        x,y,w,h = cv2.boundingRect(cnt)
#        center = (int(w/2),int(h/2))
#        if h>w:
#          radius = int(w/2)
#          cv2.circle(background,center,radius,(255,255,255),-1)
#          circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, circle_contour, hierarchy
#        else:
#          radius = int(h/2)
#          cv2.circle(background,center,radius,(255,255,255),-1)
#          circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, circle_contour, hierarchy
#      elif shape== 'ellipse':
#        x,y,w,h = cv2.boundingRect(cnt)
#        center = (int(w/2),int(h/2))
#        if w>h:
#          cv2.ellipse(background,center,(w/2,h/2),0,0,360, (0,255,0), 2)
#          ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, ellipse_contour, hierarchy
#        else:
#          cv2.ellipse(ori_img,center,(h/2,w/2),0,0,360, (0,255,0), 2)
#          cv2.ellipse(background,center,(h/2,w/2),0,0,360, (0,255,0), 2)
#          ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, ellipse_contour, hierarchy
#      else:
#          fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')
#
#   #If the user wants to change the size of the ROI or adjust ROI position
#  if adjust==True:
#    sys.stderr.write('WARNING: Make sure ROI is COMPLETELY in frame or object detection will not perform properly\n')
#    if x_adj==0 and y_adj==0 and w_adj==0 and h_adj==0:
#      fatal_error( 'If adjust is true then x_adj, y_adj, w_adj or h_adj must have a non-zero value')
#    else:
#      for cnt in roi_contour:
#        size = ix,iy, 3
#        background = np.zeros(size, dtype=np.uint8)
#        if shape=='rectangle':
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          cv2.rectangle(background,(x1,y1),(x+w1,y+h1),(0,255,0),1)
#          rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, rect_contour, hierarchy
#        elif shape== 'circle':
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          center = (int((w+x1)/2),int((h+y1)/2))
#          if h>w:
#            radius = int(w1/2)
#            cv2.circle(background,center,radius,(255,255,255),-1)
#            circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, circle_contour, hierarchy
#          else:
#            radius = int(h1/2)
#            cv2.circle(background,center,radius,(255,255,255),-1)
#            circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, circle_contour, hierarchy
#        elif shape== 'ellipse':
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          center = (int((w+x1)/2),int((h+y1)/2))
#          if w>h:
#            cv2.ellipse(background,center,(w1/2,h1/2),0,0,360, (0,255,0), 2)
#            ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, ellipse_contour, hierarchy
#          else:
#            cv2.ellipse(background,center,(h1/2,w1/2),0,0,360, (0,255,0), 2)
#            ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, ellipse_contour, hierarchy
#        else:
#            fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')
Example #15
0
def test_plantcv_fatal_error():
    # Verify that the fatal_error function raises a RuntimeError
    with pytest.raises(RuntimeError):
        pcv.fatal_error("Test error")
Example #16
0
def handle_vis_output(directory,imgtype,outdir,action):
  # directory = path to directory you want to grab images from
  # imgtype = type of output image you want to move or copy (options are rgb_slice, pseudo_on_img, pseudo_on_white, shapes, or, histogram)
  # outdir = where you want the images to go
  # action = either 'copy' or 'move'
  
  if imgtype=='rgb_slice':
    path=str(directory)
    opendir=os.listdir(path)
    for filename in opendir:
      if re.search("rgb_norm_slice\.png$",filename):
        fromDirectory = str(directory)+str(filename)
        toDirectory = str(outdir)+str(filename)
        if action=='copy':
          distutils.file_util.copy_file(fromDirectory, toDirectory)
        elif action=='move':
          distutils.file_util.move_file(fromDirectory, toDirectory)
        else:
          pcv.fatal_error('action' + (str(action) + ' is not move or copy'))
      else:
        pcv.fatal_error("Sorry no "+str(imgtype)+ " images found")
  elif imgtype=='pseudo_on_img':
    path=str(directory)
    opendir=os.listdir(path)
    for filename in opendir:
      if re.search("pseudo_on_img\.png$",filename):
        fromDirectory = str(directory)+str(filename)
        toDirectory = str(outdir)+str(filename)
        if action=='copy':
          distutils.file_util.copy_file(fromDirectory, toDirectory)
        elif action=='move':
          distutils.file_util.move_file(fromDirectory, toDirectory)
        else:
          pcv.fatal_error('action' + (str(action) + ' is not move or copy'))
      else:
        pcv.fatal_error("Sorry no "+str(imgtype)+ " images found")
  elif imgtype=='pseudo_on_white':
    path=str(directory)
    opendir=os.listdir(path)
    for filename in opendir:
      if re.search("pseudo_on_white\.png$",filename):
        fromDirectory = str(directory)+str(filename)
        toDirectory = str(outdir)+str(filename)
        if action=='copy':
          distutils.file_util.copy_file(fromDirectory, toDirectory)
        elif action=='move':
          distutils.file_util.move_file(fromDirectory, toDirectory)
        else:
          pcv.fatal_error('action' + (str(action) + ' is not move or copy'))
      else:
        pcv.fatal_error("Sorry no "+str(imgtype)+ " images found")
  elif imgtype=='shapes':
    path=str(directory)
    opendir=os.listdir(path)
    for filename in opendir:
      if re.search("shapes\.png$",filename):
        fromDirectory = str(directory)+str(filename)
        toDirectory = str(outdir)+str(filename)
        if action=='copy':
          distutils.file_util.copy_file(fromDirectory, toDirectory)
        elif action=='move':
          distutils.file_util.move_file(fromDirectory, toDirectory)
        else:
          pcv.fatal_error('action' + (str(action) + ' is not move or copy'))
      else:
        pcv.fatal_error("Sorry no "+str(imgtype)+ " images found")
  elif imgtype=='histogram':
    path=str(directory)
    opendir=os.listdir(path)
    for filename in opendir:
      if re.search("hist\.png$",filename):
        fromDirectory = str(directory)+str(filename)
        toDirectory = str(outdir)+str(filename)
        if action=='copy':
          distutils.file_util.copy_file(fromDirectory, toDirectory)
        elif action=='move':
          distutils.file_util.move_file(fromDirectory, toDirectory)
        else:
          pcv.fatal_error('action' + (str(action) + ' is not move or copy'))
      else:
        pcv.fatal_error("Sorry no "+str(imgtype)+ " images found")
  else:
    pcv.fatal_error('imgtype' + (str(imgtype) + ' is not rgb_slice, pseudo_on_img, pseudo_on_white, shapes, or, histogram!'))
Example #17
0
  # Get the headers for metadata and headers for features these will be the headers of features table
    metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                  'metadata.image_id=analysis_images.image_id where analysis_images.type=="mask" '
                                 'and metadata.imgtype=="VIS"', db)
  elif imgtype=="NIR":
  # Get the headers for metadata and headers for features these will be the headers of features table
    metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                  'metadata.image_id=analysis_images.image_id where analysis_images.type=="mask" '
                                 'and metadata.imgtype=="NIR"', db)
  elif imgtype=="None":
  # Get the headers for metadata and headers for features these will be the headers of features table
    metaimages = pd.read_sql_query('SELECT * FROM metadata INNER JOIN analysis_images ON '
                                  'metadata.image_id=analysis_images.image_id where analysis_images.type=="mask" '
                                 'and metadata.imgtype=="none"', db)
  else:
    pcv.fatal_error("imgtype is not VIS, NIR or None")

  sorted=metaimages.sort_values(['timestamp'])

  nrowsorted=sorted.shape[0]

  chunksfactor=nrowsorted/float(random)

  random_index_list=[]

  for i in range(2,random+1,1):
      x=int((i-1)*chunksfactor)
      y=int((i)*chunksfactor)
      randnum=randrange(x,y)
      random_index_list.append(randnum)
Example #18
0
def test_plantcv_fatal_error():
    # Verify that the fatal_error function raises a RuntimeError
    with pytest.raises(RuntimeError):
        pcv.fatal_error("Test error")
Example #19
0
def define_multi_roi(img, device, debug=False, roi_file=None, roi_input='default', rows=None, col=None, shape=None, rad=None, dist_x=None, dist_y=None, adjust_x=False, adjust_y=False):
  #If you have very irregularly spaced ROI (that stays consistent between images), it is likely easiest to provide a file with an ROI
  #But remember that the ROIs can capture objects outside of their borders as long as the object is connected (partially inside ROI) so some irregularities are fine
  
  # img= img to overlay roi
  # roi_file= default is None, else the user can input an ROI image, object area shoud be white and background area should be black.
  # roi_input= type of image that the roi_file is, either 'binary', 'rgb' or 'default' (no ROI inputted)
  # debug= True/False, if True, print image
  # rows= number of rows of rois
  # col= number of columns of rois
  # shape= None, 'circle', or 'square'
  # rad= radius or height/width of shape
  # dist_x= distance between edges on the x axis
  # dist_y= distance between edges on the y axis
  # adjust_x= distance to move set of roi in the x direction
  # adjust_y= distance to move set of roi in the y direction
  
  device +=1
  
  ori_img=np.copy(img)
  if len(np.shape(img))==3:
    ix,iy,iz=np.shape(img)
  else:
    ix,iy=np.shape(img)

  #Allows user to use the default ROI or input their own RGB or binary image (made with imagej or some other program) as a base ROI (that can be adjusted below if necessary)
  if roi_input== 'rgb':
    hsv = cv2.cvtColor(roi_file, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(hsv)
    ret,v_img = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY)
    roi_contour,roi_hierarchy = cv2.findContours(v_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    if debug:
      print_image(roi_file, (str(device) + '_roi.png'))
  elif roi_input== 'binary':
    roi_contour,roi_hierarchy = cv2.findContours(roi_file,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    if debug:
      print_image(roi_file, (str(device) + '_roi.png'))
  elif roi_input=='default':
    size = ix,iy
    roi_background = np.zeros(size, dtype=np.uint8)
    roi_size=(ix-5),(iy-5)
    roi=np.zeros(roi_size, dtype=np.uint8)
    roi1=roi+1
    roi_contour,roi_heirarchy=cv2.findContours(roi1,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(roi_background,roi_contour[0],-1, (255,0,0),5)
  else:
    fatal_error('ROI Input' + str(roi_input) + ' is not "binary", "rgb" or "default roi"!')
  
  
  print roi_contour
  print v
  
  ##If the ROI is exactly in the 'correct' position 
  #if adjust_x==False and adjust_y==False:
  #  if roi_input=='rgb' or roi_input=='binary':
  #    size = ix,iy,3
  #    background = np.zeros(size, dtype=np.uint8)
  #    roi_contour1=roi_contour+background
  #    roi_heirarchy1=roi_heirarchy
  #    cv2.drawContours(ori_img,roi_contour1[0],-1,(255,0,0),5)
  #    if debug:
  #      print_image(ori_img,(str(device)+'ori_roi.png'))
  #    #return device,roi_contour1,roi_heirarchy1
    
    
    #for cnt in roi_contour:
    #  size = ix,iy,3
    #  background = np.zeros(size, dtype=np.uint8)
    #  if shape=='square':
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    cv2.rectangle(background,(x,y),(x+w,y+h),(0,255,0),5)
    #    rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #    rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #    cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
    #    if debug:
    #      print_image(ori_img, (str(device) + '_roi.png'))
    #    return device, rect_contour, hierarchy
    #  elif shape== 'circle':
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    center = (int(w/2),int(h/2))
    #    if h>w:
    #      radius = int(w/2)
    #      cv2.circle(background,center,radius,(255,255,255),-1)
    #      circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, circle_contour, hierarchy
    #    else:
    #      radius = int(h/2)
    #      cv2.circle(background,center,radius,(255,255,255),-1)
    #      circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, circle_contour, hierarchy
    #  elif shape== 'ellipse': 
    #    x,y,w,h = cv2.boundingRect(cnt)
    #    center = (int(w/2),int(h/2))
    #    if w>h:
    #      cv2.ellipse(background,center,(w/2,h/2),0,0,360, (0,255,0), 2)
    #      ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, ellipse_contour, hierarchy
    #    else:
    #      cv2.ellipse(ori_img,center,(h/2,w/2),0,0,360, (0,255,0), 2)
    #      cv2.ellipse(background,center,(h/2,w/2),0,0,360, (0,255,0), 2)
    #      ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
    #      ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    #      cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
    #      if debug:
    #        print_image(ori_img, (str(device) + '_roi.png'))
    #      return device, ellipse_contour, hierarchy
    #  else:
    #      fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')


  #Adjust ROI moves the inputted or created ROI
  

  return device

#def define_roi(img, shape, device, roi=None, roi_input='default', debug=False, adjust=False, x_adj=0, y_adj=0, w_adj=0, h_adj=0):
#  # img = img to overlay roi 
#  # roi =default (None) or user input ROI image, object area should be white and background should be black, has not been optimized for more than one ROI
#  # roi_input = type of file roi_base is, either 'binary', 'rgb', or 'default' (no ROI inputted)
#  # shape = desired shape of final roi, either 'rectangle' or 'circle', if  user inputs rectangular roi but chooses 'circle' for shape then a circle is fitted around rectangular roi (and vice versa)
#  # device = device number.  Used to count steps in the pipeline
#  # debug = True/False. If True, print image
#  # adjust= either 'True' or 'False', if 'True' allows user to adjust ROI
#  # x_adj = adjust center along x axis
#  # y_adj = adjust center along y axis
#  # w_adj = adjust width
#  # h_adj = adjust height
#
#  device += 1
#  ori_img=np.copy(img)
#  if len(np.shape(img))==3:
#    ix,iy,iz=np.shape(img)
#  else:
#    ix,iy=np.shape(img)
#  
#  #Allows user to use the default ROI or input their own RGB or binary image (made with imagej or some other program) as a base ROI (that can be adjusted below)
#  if roi_input== 'rgb':
#    hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
#    h,s,v = cv2.split(hsv)
#    ret,v_img = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY)
#    roi_contour,hierarchy = cv2.findContours(v_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#  elif roi_input== 'binary':
#    roi_contour,hierarchy = cv2.findContours(rois,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)  
#  elif roi_input=='default':
#    size = ix,iy
#    roi_background = np.zeros(size, dtype=np.uint8)
#    roi_size=(ix-5),(iy-5)
#    roi=np.zeros(roi_size, dtype=np.uint8)
#    roi1=roi+1
#    roi_contour,roi_heirarchy=cv2.findContours(roi1,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#    cv2.drawContours(roi_background,roi_contour[0],-1, (255,0,0),5)
#    if adjust==True:
#      if x_adj>0 and w_adj>0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#      elif y_adj>0 and h_adj>0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#      elif x_adj<0 or y_adj<0:
#        fatal_error('Adjusted ROI position is out of frame, this will cause problems in detecting objects')
#  else:
#    fatal_error('ROI Input' + str(roi_input) + ' is not "binary", "rgb" or "default roi"!')
#    
#  #If the ROI is exactly in the 'correct' position 
#  if adjust==False:    
#    for cnt in roi_contour:
#      size = ix,iy,3
#      background = np.zeros(size, dtype=np.uint8)
#      if shape=='rectangle':
#        x,y,w,h = cv2.boundingRect(cnt)
#        cv2.rectangle(background,(x,y),(x+w,y+h),(0,255,0),5)
#        rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#        rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#        cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
#        if debug:
#          print_image(ori_img, (str(device) + '_roi.png'))
#        return device, rect_contour, hierarchy
#      elif shape== 'circle':
#        x,y,w,h = cv2.boundingRect(cnt)
#        center = (int(w/2),int(h/2))
#        if h>w:
#          radius = int(w/2)
#          cv2.circle(background,center,radius,(255,255,255),-1)
#          circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, circle_contour, hierarchy
#        else:
#          radius = int(h/2)
#          cv2.circle(background,center,radius,(255,255,255),-1)
#          circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, circle_contour, hierarchy
#      elif shape== 'ellipse': 
#        x,y,w,h = cv2.boundingRect(cnt)
#        center = (int(w/2),int(h/2))
#        if w>h:
#          cv2.ellipse(background,center,(w/2,h/2),0,0,360, (0,255,0), 2)
#          ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, ellipse_contour, hierarchy
#        else:
#          cv2.ellipse(ori_img,center,(h/2,w/2),0,0,360, (0,255,0), 2)
#          cv2.ellipse(background,center,(h/2,w/2),0,0,360, (0,255,0), 2)
#          ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, ellipse_contour, hierarchy
#      else:
#          fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')
#          
#   #If the user wants to change the size of the ROI or adjust ROI position   
#  if adjust==True:
#    sys.stderr.write('WARNING: Make sure ROI is COMPLETELY in frame or object detection will not perform properly\n')
#    if x_adj==0 and y_adj==0 and w_adj==0 and h_adj==0:
#      fatal_error( 'If adjust is true then x_adj, y_adj, w_adj or h_adj must have a non-zero value')
#    else:
#      for cnt in roi_contour:
#        size = ix,iy, 3
#        background = np.zeros(size, dtype=np.uint8)
#        if shape=='rectangle':
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          cv2.rectangle(background,(x1,y1),(x+w1,y+h1),(0,255,0),1)
#          rect = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#          rect_contour,hierarchy = cv2.findContours(rect,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#          cv2.drawContours(ori_img,rect_contour[0],-1, (255,0,0),5)
#          if debug:
#            print_image(ori_img, (str(device) + '_roi.png'))
#          return device, rect_contour, hierarchy
#        elif shape== 'circle':
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          center = (int((w+x1)/2),int((h+y1)/2))
#          if h>w:
#            radius = int(w1/2)
#            cv2.circle(background,center,radius,(255,255,255),-1)
#            circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, circle_contour, hierarchy
#          else:
#            radius = int(h1/2)
#            cv2.circle(background,center,radius,(255,255,255),-1)
#            circle = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            circle_contour,hierarchy = cv2.findContours(circle,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,circle_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, circle_contour, hierarchy
#        elif shape== 'ellipse': 
#          x,y,w,h = cv2.boundingRect(cnt)
#          x1=x+x_adj
#          y1=y+y_adj
#          w1=w+w_adj
#          h1=h+h_adj
#          center = (int((w+x1)/2),int((h+y1)/2))
#          if w>h:
#            cv2.ellipse(background,center,(w1/2,h1/2),0,0,360, (0,255,0), 2)
#            ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, ellipse_contour, hierarchy
#          else:
#            cv2.ellipse(background,center,(h1/2,w1/2),0,0,360, (0,255,0), 2)
#            ellipse = cv2.cvtColor( background, cv2.COLOR_RGB2GRAY )
#            ellipse_contour,hierarchy = cv2.findContours(ellipse,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#            cv2.drawContours(ori_img,ellipse_contour[0],-1, (255,0,0),5)
#            if debug:
#              print_image(ori_img, (str(device) + '_roi.png'))
#            return device, ellipse_contour, hierarchy
#        else:
#            fatal_error('Shape' + str(shape) + ' is not "rectangle", "circle", or "ellipse"!')