print "      Wrapper: %s" % totalCandies[w][1]
            print " Wrapper Conf: %s" % totalCandies[w][3]
            print "        Score: %s" % totalCandies[w][2]

            displayname = "%s" % w
            scorestring = "%s" % totalCandies[w][2]
            wrapperscore = totalCandies[w][1]*100
            wrapperstring = "%.3f" % wrapperscore
            wrapperconf = "%.3f" % totalCandies[w][3]

            x_start = (loc[0] - dist_full)*scale
            x_end = (loc[0] + dist_full)*scale
            y_start = (loc[1] - dist_full)*scale
            y_end = (loc[1] + dist_full)*scale

            cv2.putText(scaled_img,displayname,(int(x_start+1),int(y_start+25)),font,0.75,(0,255,255), 3, 8);
            cv2.putText(scaled_img,scorestring,(int(x_start+1),int(y_end-1)),font,0.75,(0,255,0), 3, 8);
            cv2.putText(scaled_img,wrapperstring,(int(x_end-75),int(y_start+25)),font,0.75,(255,255,0), 3, 8);
            cv2.putText(scaled_img,wrapperconf,(int(x_end-75),int(y_end-1)),font,0.75,(255,0,255), 3, 8);
            cv2.rectangle(scaled_img,(int(x_start),int(y_start)),(int(x_end),int(y_end)),(0,255,255),1)

        cv2.imwrite("Test_Images/Output_Images/5_circled_image.jpg",scaled_img)
        shrink, temp = ScaleImage.scale(scaled_img,1000)

        showImage.showImage(shrink)    
    else:
        print "No circles detected."

if __name__ == '__main__':
    combined(sys.argv[1], sys.argv[2])
def combined(inputfile, debug=False):
    start_file = inputfile
    img = cv2.imread(start_file)
    full_img = cv2.imread(start_file)

    original_img = deepcopy(img)

    fullheight, fullwidth, fullchannels = full_img.shape
    print "fullwidth %s" % fullwidth
    print "fullheight %s" % fullheight

    img, scale = ScaleImage.scale(full_img,1000)
    height, width, channels = img.shape
    scaled_img = deepcopy(img)

    ##First blur image in order to reduce noise
    blurred_img = deepcopy(img)

    print "Blurring image for filtering"
    blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0)
    blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0)
    blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0)
    print "Blurring done"

    cv2.imwrite("Test_Images/Output_Images/blurred_img.jpg", blurred_img)


    ##Then find the average background color
    print "Calibrating color filtration"
    red,green,blue = Calibrate.findRed(blurred_img)

    ##Filter the image based on that average color
    print "Filtering blurred image"
    blurred_img = FilterImage.filter(blurred_img,red,green,blue)

    if (debug):
        showImage.showImage(blurred_img)

    ##Mask the original image based on the the blurred filter
    print "Masking original image based on blurred image"
    for y in range(0,height):
        for x in range(0,width):
            pxR = blurred_img[y,x,2]
            pxB = blurred_img[y,x,1]
            pxG = blurred_img[y,x,0]
            if ( (pxR == 0) and (pxG == 0) and (pxB == 0) ):
                img[y,x] = 0

    cv2.imwrite("Test_Images/Output_Images/justFiltered.jpg", img)

    if (debug):
        showImage.showImage(img, "Just filtered")

    morpher = ImageMorpher()

    openimg = deepcopy(img)

    ## Use morphology to get rid of erratic blobs and specs
    print "Doing morphology to fix blobbies"
    openimg = morpher.openWithSquare(openimg,7)

    openimg = morpher.closeWithSquare(openimg,7)

    openimg = cv2.cvtColor(openimg,cv2.COLOR_BGR2GRAY)

    for x in range(0,height):
        for y in range(0,width):
            px = openimg[x,y]
            if ( (px == 0) ):
                openimg[x,y] = 0
            else:
                openimg[x,y] = 255

    ##Get contours for remaining blobs
    print "Contouring blobbies"
    contoured_img, contours, hierarchy = cv2.findContours(openimg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    ##Get rid of the tiny remaining specs
    print "Removing small blobs"
    for i in range(0, len(contours)):
        cnt = contours[i]
        if (cv2.contourArea(cnt) < 2000):
            cv2.drawContours(contoured_img,cnt,-1,0,thickness=cv2.FILLED)

    ##Create a new mask to remove contours
    print "Masking image based on removed contours"
    for x in range(0,height):
        for y in range(0,width):
            px = contoured_img[x,y]
            if ( (px == 0) ):
                img[x,y] = [0,0,0]
            else:
                continue

    if (debug):
        showImage.showImage(img, "Filtered and corrected")

    color_filtered_img = deepcopy(img)
    cv2.imwrite("Test_Images/Output_Images/1_Template_Color_Filtered.jpg",img)

    temp = deepcopy(color_filtered_img)


    ##Watershed works best with blurred image
    print "Blurring image for watershed algorithm"
    img = cv2.GaussianBlur(img,(9,9),0)
    img = cv2.GaussianBlur(img,(9,9),0)

    #####
    #Watershed segmentation
                           
    b,g,r = cv2.split(img)
    rgb_img = cv2.merge([r,g,b])

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    # noise removal
    kernel = np.ones((2,2),np.uint8)
    closing = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel, iterations = 2)

    # sure background area
    sure_bg = cv2.dilate(closing,kernel,iterations=1)

    # Finding sure foreground area
    dist_transform = cv2.distanceTransform(sure_bg,cv2.DIST_L2,3)

    # Threshold
    ret, sure_fg = cv2.threshold(dist_transform,0.1*dist_transform.max(),255,0)

    # Finding unknown region
    sure_fg = np.uint8(sure_fg)
    unknown = cv2.subtract(sure_bg,sure_fg)

    # Marker labelling
    ret, markers = cv2.connectedComponents(sure_fg)

    # Add one to all labels so that sure background is not 0, but 1
    markers = markers+1

    # Now, mark the region of unknown with zero
    markers[unknown==255] = 0

    markers = cv2.watershed(img,markers)
    img[markers == -1] = [255,0,0]

    cv2.imwrite('Test_Images/Output_Images/2_Template_Watershedded.jpg',img)

    if (debug):
        showImage.showImage(img,"Template_Watershedded")

    water_img = deepcopy(img)

    new_img = img

    for x in range(1,height-1):
        for y in range(1,width-1):
            if markers[x,y] == -1:
                new_img[x,y] = [255,255,255]
            else:
                new_img[x,y] = [0,0,0]

    cv2.imwrite('Test_Images/Output_Images/3_Template_Just_Watershed_Edges.jpg',new_img)


    #####
    #Hough Circles
    print "Doing Hough cirlces on watershedded edges"
    scimg = cv2.imread('Test_Images/Output_Images/3_Template_Just_Watershed_Edges.jpg',0)
    #scimg = cv2.medianBlur(scimg,5)
    sccimg = cv2.cvtColor(scimg,cv2.COLOR_GRAY2BGR)

    circles = cv2.HoughCircles(scimg,cv2.HOUGH_GRADIENT,1,100,
                                param1=50,param2=20,minRadius=30,maxRadius=100)
    ##circles = cv2.HoughCircles(scimg,cv2.HOUGH_GRADIENT,1,50,
    ##                            param1=50,param2=15,minRadius=15,maxRadius=50)

    counter = 0

    radsum = 0

    try:    
        print circles.shape
    except Exception, e:
        print e
def findRed ( image ):
    redimg = deepcopy(image)
    whiteimg = deepcopy(image)
    redscimg,scale = ScaleImage.scale(redimg, 500)
    whitescimg,scale = ScaleImage.scale(whiteimg, 500)
    #scimg = img

    height, width, channels = redscimg.shape

    RedSum = 0
    GreenSum = 0
    BlueSum = 0
    for x in range(0,height):
        for y in range(0,width):
            pxR = redscimg[x,y,2]
            pxG = redscimg[x,y,1]
            pxB = redscimg[x,y,0]
            RedSum = RedSum + pxR
            GreenSum = GreenSum + pxG
            BlueSum = BlueSum + pxB
            #x += 1

    avgRed = RedSum/(height*width/2)
    avgGreen = GreenSum/(height*width/2)
    avgBlue = BlueSum/(height*width/2)

    print "Average RGB: (%s,%s,%s)" % (avgRed,avgGreen,avgBlue)

    #cv2.namedWindow('image')

    r = avgRed + 25
    b = avgGreen - 50
    g = avgBlue - 50

    # create trackbars for color change
    cv2.createTrackbar('R','image',0,255,nothing)
    cv2.setTrackbarPos('R','image',r)
    cv2.createTrackbar('B','image',0,255,nothing)
    cv2.setTrackbarPos('B','image',b)
    cv2.createTrackbar('G','image',0,255,nothing)
    cv2.setTrackbarPos('G','image',g)

    r = 0;
    pastr = 0;

    r = cv2.getTrackbarPos('R','image')
    b = cv2.getTrackbarPos('B','image')
    g = cv2.getTrackbarPos('G','image')

    print "Red value: %s" % r
    print "Green value: %s" % g
    print "Blue value: %s" % b

##    cv2.imshow('image',scimg)
##    
##    while(1):
##        #cv2.imshow('image',scimg)
##        k = cv2.waitKey(1) & 0xFF
##        if k == 27:
##            break
##
##        pastr = r
##        r = cv2.getTrackbarPos('R','image')
##        b = cv2.getTrackbarPos('B','image')
##        g = cv2.getTrackbarPos('G','image')
##
##        if pastr != r:
##            #cv2.imshow('image',scimg)
##            #k = cv2.waitKey(1) & 0xFF
##            #if k == 27:
##            #    break
##            print "updated!"        
##
##        for x in range(0,height):
##            for y in range(0,width):
##                pxR = scimg[x,y,2]
##                pxG = scimg[x,y,1]
##                pxB = scimg[x,y,0]
##
##                #if  not REALLY white or not REALLY red
##
##                #if ((pxR >= 200) & (pxB >= 200) & (pxG >= 200)):
##                #    reallyWhite = True
##                #else:
##                #    reallyWhite = False
##
##                #if ((pxR >= pxB + 75) & (pxR >= pxG +75) & (pxR >= 150)):
##                #    reallyRed = True
##                #else:
##                #    reallyRed = False
##    
##                #if ~reallyWhite & ~reallyRed:
##                #    scimg[x,y] = [0,0,0]
##                
##                if ((~(pxR >= r)) | (~(pxG >= g)) | (~(pxB >= b))):
##                    if (~((pxR >= pxB + 75) & (pxR >= pxG +75) & (pxR >=150))):
##                        scimg[x,y] = [0,0,0]
##
##                if ((pxR <= 175) & (pxB <= 175) & (pxG <= 175)):
##                    scimg[x,y] = [0,0,0]
##
##    cv2.destroyAllWindows()



    return r,g,b