def detectEdgesInColorPlanes(self, imageToSplit, colorPlane="red"):

        morpher = ImageMorpher()
        channels = cv2.split(imageToSplit)

        colorEdges = []

        for i in range(len(channels)):
            blurred = cv2.GaussianBlur(channels[i], (7, 7), 3)
            colorEdges.append(morpher.dilateWithSquare(cv2.Canny(blurred, 50, 100), 3))

        if (colorPlane == "red"):
            print 'anding'
            result = cv2.bitwise_and(colorEdges[0], colorEdges[1])
            result = morpher.closeWithSquare(result, 2)
            #self.showImage(result)
            result = cv2.bitwise_and(result, cv2.bitwise_not(colorEdges[2]))
        elif (colorPlane == "green"):
            result = cv2.bitwise_and(colorEdges[0], colorEdges[2])
            result = morpher.closeWithSquare(result, 2)
            result = cv2.bitwise_and(result, cv2.bitwise_not(colorEdges[1]))
        elif (colorPlane == "blue"):
            result = cv2.bitwise_and(colorEdges[1], colorEdges[2])
            result = morpher.closeWithSquare(result, 2)
            result = cv2.bitwise_and(result, cv2.bitwise_not(colorEdges[0]))
        #self.showImage(result)
        result = morpher.openWithSquare(result, 2)
        #self.showImage(result)

        return result
    def cutOutNonRed(self, imageToCut):
        redHighlighted = self.highlightDarkRed(imageToCut, 160, -1, 180, 20, False)

        #self.showImage(redHighlighted)
        morpher = ImageMorpher()
        #self.showImage(redHighlighted)
        mask1 = morpher.dilateWithSquare(redHighlighted, 10)
        #self.showImage(mask1)
        mask1 = morpher.closeWithSquare(mask1, 50)
        #self.showImage(mask1)
        maskedImg = cv2.bitwise_and(imageToCut, imageToCut, mask=mask1)
        #self.showImage(maskedImg)

        gray = self.convertColorToGrayscale(imageToCut)
        blurred = cv2.GaussianBlur(gray, (5, 5), 3)
        edges = cv2.Canny(blurred, 50, 100)
        #self.showImage(edges)
        mask2 = morpher.dilateWithSquare(edges, 10)
        #self.showImage(mask2)
        mask2 = morpher.closeWithSquare(mask2, 50)
        #self.showImage(mask2)

        secondMaskedImg = cv2.bitwise_and(maskedImg, maskedImg, mask=mask2)
        #self.showImage(secondMaskedImg)

        totalMask = cv2.bitwise_and(mask1, mask2)
        #self.showImage(totalMask)
        totalMask = morpher.operateWithVerticalLine(totalMask, morpher.DILATION, 15)
        totalMask = morpher.operateWithHorizontalLine(totalMask, morpher.DILATION, 15)
        #self.showImage(totalMask)
        totalMask = morpher.openWithSquare(totalMask, 20)
        #self.showImage(totalMask)

        totalMask = morpher.closeWithSquare(totalMask, 40)
        #self.showImage(totalMask)

        result = cv2.bitwise_and(imageToCut, imageToCut, mask=totalMask)
        #self.showImage(result)
        return result
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