Exemplo n.º 1
0
def hsvProceed(img, camID):
    single = cv.CreateImage(cv.GetSize(img), 8, 1)
    single_c = cv.CreateImage(cv.GetSize(img), 8, 1)
    if camID == 0:
        v_min = 120
    if camID == 1:
        v_min = 100
    width = 0
    height = 0
    while (1):
        while (1):
            if (img[height, width][0] >
                    95) and (img[height, width][0] <
                             140) and (img[height, width][1] > 40) and (
                                 img[height, width][1] <
                                 220) and (img[height, width][2] > v_min):
                single[height, width] = 255.0
                single_c[height, width] = 255.0
            else:
                single[height, width] = 0.0
                single_c[height, width] = 0.0
            height = height + 1
            if (height == 480):
                height = 0
                break
        width = width + 1
        if (width == 640):
            break
    cv.Erode(single, single)
    cv.Dilate(single, single)
    # cv.Erode(single_c, single_c)
    # cv.Dilate(single_c, single_c)
    # cv.ShowImage("rgb",single)
    # cv.WaitKey()
    return single, single_c
Exemplo n.º 2
0
def hsvProceed(img):
    single = cv.CreateImage(cv.GetSize(img), 8, 1)
    single_c = cv.CreateImage(cv.GetSize(img), 8, 1)
    width = 0
    height = 0
    while (1):
        while (1):
            if (img[height, width][0] >
                    70) and (img[height, width][0] <
                             95) and (img[height, width][1] > 53) and (
                                 img[height, width][1] <
                                 230):  #and(img[height,width][2]<200):
                single[height, width] = 255
                single_c[height, width] = 255
            else:
                single[height, width] = 0
                single_c[height, width] = 0
            height = height + 1
            if (height == 480):
                height = 0
                break
        width = width + 1
        if (width == 640):
            break
    cv.Erode(single, single)
    cv.Dilate(single, single)
    cv.Erode(single_c, single_c)
    cv.Dilate(single_c, single_c)
    # cv.ShowImage("rgb",single)
    # cv.WaitKey()
    return single, single_c
Exemplo n.º 3
0
def getIris(frame):
	iris = []
	copyImg = cv.CloneImage(frame)
	resImg = cv.CloneImage(frame)
	grayImg = cv.CreateImage(cv.GetSize(frame), 8, 1)
	mask = cv.CreateImage(cv.GetSize(frame), 8, 1)
	storage = cv.CreateMat(frame.width, 1, cv.CV_32FC3)
	cv.CvtColor(frame,grayImg,cv.CV_BGR2GRAY)
	cv.Canny(grayImg, grayImg, 5, 70, 3)
	cv.Smooth(grayImg,grayImg,cv.CV_GAUSSIAN, 7, 7)
	circles = getCircles(grayImg)
	iris.append(resImg)
	for circle in circles:
		rad = int(circle[0][2])
		global radius
		radius = rad
		cv.Circle(mask, centroid, rad, cv.CV_RGB(255,255,255), cv.CV_FILLED)
		cv.Not(mask,mask)
		cv.Sub(frame,copyImg,resImg,mask)
		x = int(centroid[0] - rad)
		y = int(centroid[1] - rad)
		w = int(rad * 2)
		h = w
		cv.SetImageROI(resImg, (x,y,w,h))
		cropImg = cv.CreateImage((w,h), 8, 3)
		cv.Copy(resImg,cropImg)
		cv.ResetImageROI(resImg)
		return(cropImg)
	return (resImg)
Exemplo n.º 4
0
    def __init__(self, threshold=1, doRecord=True, showWindows=True):
        self.writer = None
        self.font = None
        self.doRecord = doRecord  # Either or not record the moving object
        self.show = showWindows  # Either or not show the 2 windows
        self.frame = None

        self.capture = cv.CaptureFromCAM(0)
        self.frame = cv.QueryFrame(
            self.capture)  # Take a frame to init recorder
        if doRecord:
            self.initRecorder()
        self.gray_frame = cv.CreateImage(cv.GetSize(self.frame),
                                         cv.IPL_DEPTH_8U, 1)
        self.average_frame = cv.CreateImage(cv.GetSize(self.frame),
                                            cv.IPL_DEPTH_32F, 3)
        self.absdiff_frame = None
        self.previous_frame = None

        self.surface = self.frame.width * self.frame.height
        self.currentsurface = 0
        self.currentcontours = None
        self.threshold = threshold
        self.isRecording = False
        self.trigger_time = 0  # Hold timestamp of the last detection
        if showWindows:
            cv.NamedWindow("Image")
            cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold,
                              100, self.onThresholdChange)
Exemplo n.º 5
0
def getthresholdedimg(im):
    imghsv = cv.CreateImage(cv.GetSize(im), 8, 3)
    # Convert image from RGB to HSV
    cv.CvtColor(im, imghsv, cv.CV_BGR2HSV)
    imgthreshold = cv.CreateImage(cv.GetSize(im), 8, 1)
    cv.InRangeS(imghsv, cv.Scalar(23, 100, 100), cv.Scalar(25, 255, 255),
                imgthreshold)  # catch the orange yellow blob
    return imgthreshold
Exemplo n.º 6
0
def hsvProceed(img, camID):  #img为一三通道的HSV图像,camID
    #初始化
    v_min = 0
    h_max = 0
    h_min = 0
    s_max = 0
    s_min = 0
    width = 0
    height = 0
    #创建两个单通道图像
    single = cv2.CreateImage(cv2.GetSize(img), 8, 1)
    single_c = cv2.CreateImage(cv2.GetSize(img), 8, 1)
    #为不同的摄像头分别设置h,s,v的阈值区间
    if camID == 0:
        v_min = 120
        h_max = 138
        h_min = 95
        s_max = 256
        s_min = 30
    if camID == 1:
        v_min = 10
        h_max = 140
        h_min = 95
        s_max = 256
        s_min = 30

# 提取红色部分到single,组建单通道图像

    while (1):
        while (1):
            if (img[height, width][0] >=
                    h_min) and (img[height, width][0] < h_max) and (
                        img[height, width][1] >=
                        s_min) and (img[height, width][1] < s_max) and (
                            img[height, width][2] >= v_min):  #筛选红色部分
                single[height, width] = 255.0
                single_c[height, width] = 255.0
            else:
                single[height, width] = 0.0
                single_c[height, width] = 0.0
            height = height + 1
            if (height == 480):
                height = 0
                break
        width = width + 1
        if (width == 640):
            break
#形态学处理
    cv2.Erode(single, single)
    cv2.Dilate(single, single)

    return single, single_c
Exemplo n.º 7
0
    def run(self):
        while True:
            img = self.capture.read()

            #blur the source image to reduce color noise
            cv2.blur(img, img, 3)

            #convert the image to hsv(Hue, Saturation, Value) so its
            #easier to determine the color to track(hue)
            hsv_img = cv2.CreateImage(cv2.GetSize(img), 8, 3)
            cv2.CvtColor(img, hsv_img, cv2.CV_BGR2HSV)

            #limit all pixels that don't match our criteria, in this case we are
            #looking for purple but if you want you can adjust the first value in
            #both turples which is the hue range(120,140).  OpenCV uses 0-180 as
            #a hue range for the HSV color model
            greenLower = (20, 190, 165)
            greenUpper = (30, 225, 220)
            thresholded_img = cv2.CreateImage(cv2.GetSize(hsv_img), 8, 1)
            cv2.InRangeS(hsv_img, greenLower, greenUpper, thresholded_img)

            #determine the objects moments and check that the area is large
            #enough to be our object
            moments = cv2.Moments(thresholded_img, 0)
            area = cv2.GetCentralMoment(moments, 0, 0)

            #there can be noise in the video so ignore objects with small areas
            if (area > 100000):
                #determine the x and y coordinates of the center of the object
                #we are tracking by dividing the 1, 0 and 0, 1 moments by the area
                x = cv2.GetSpatialMoment(moments, 1, 0) / area
                y = cv2.GetSpatialMoment(moments, 0, 1) / area

                #print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area)

                #create an overlay to mark the center of the tracked object
                overlay = cv2.CreateImage(cv2.GetSize(img), 8, 3)

                cv2.Circle(overlay, (x, y), 2, (255, 255, 255), 20)
                cv2.Add(img, overlay, img)
                #add the thresholded image back to the img so we can see what was
                #left after it was applied
                cv2.Merge(thresholded_img, None, None, None, img)

            #display the image
            cv2.ShowImage(color_tracker_window, img)

            if cv2.WaitKey(10) == 27:
                break
  def __produce_gradient_image(self, i, scale):
    size = cv.GetSize(i)
    grey_image = cv.CreateImage(size, 8, 1)

    size = [s/scale for s in size]
    grey_image_small = cv.CreateImage(size, 8, 1)

    cv.CvtColor(i, grey_image, cv.CV_RGB2GRAY)

    df_dx = cv.CreateImage(cv.GetSize(i), cv.IPL_DEPTH_16S, 1)
    cv.Sobel( grey_image, df_dx, 1, 1)
    cv.Convert(df_dx, grey_image)
    cv.Resize(grey_image, grey_image_small)#, interpolation=cv.CV_INTER_NN)
    cv.Resize(grey_image_small, grey_image)#, interpolation=cv.CV_INTER_NN)
    return grey_image
def find_leds(thresh_img):
    """
    Given a binary image showing the brightest pixels in an image, 
    returns a result image, displaying found leds in from PIL import Image
a rectangle
    """
    contours = cv2.FindContours(thresh_img,
                                cv2.CreateMemStorage(),
                                mode=cv2.CV_RETR_EXTERNAL,
                                method=cv2.CV_CHAIN_APPROX_NONE,
                                offset=(0, 0))

    regions = []
    while contours:
        pts = [pt for pt in contours]
        x, y = zip(*pts)
        min_x, min_y = min(x), min(y)
        width, height = max(x) - min_x + 1, max(y) - min_y + 1
        regions.append((min_x, min_y, width, height))
        contours = contours.h_next()

        out_img = cv2.CreateImage(cv2.GetSize(grey_img), 8, 3)
    for x, y, width, height in regions:
        pt1 = x, y
        pt2 = x + width, y + height
        color = (0, 0, 255, 0)
        cv2.Rectangle(out_img, pt1, pt2, color, 2)

    return out_img, regions
def extract_bright(grey_img, histogram=False):
    """
    Extracts brightest part of the image.
    Expected to be the LEDs (provided that there is a dark background)
    Returns a Thresholded image
    histgram defines if we use the hist calculation to find the best margin
    """
    ## Searches for image maximum (brightest pixel)
    # We expect the LEDs to be brighter than the rest of the image
    [minVal, maxVal, minLoc, maxLoc] = cv2.MinMaxLoc(grey_img)
    print "Brightest pixel val is %d" % (maxVal)

    #We retrieve only the brightest part of the image
    # Here is use a fixed margin (80%), but you can use hist to enhance this one
    if 0:
        ## Histogram may be used to wisely define the margin
        # We expect a huge spike corresponding to the mean of the background
        # and another smaller spike of bright values (the LEDs)
        hist = grey_histogram(img, nBins=64)
        [hminValue, hmaxValue, hminIdx, hmaxIdx] = cv2.GetMinMaxHistValue(hist)
        margin = 0  # statistics to be calculated using hist data
    else:
        margin = 0.8

    thresh = int(maxVal * margin)  # in pix value to be extracted
    print "Threshold is defined as %d" % (thresh)

    thresh_img = cv2.CreateImage(cv2.GetSize(img), img.depth, 1)
    cv2.Threshold(grey_img, thresh_img, thresh, 255, cv2.CV_THRESH_BINARY)

    return thresh_img
Exemplo n.º 11
0
def maxValueGarylize(image):
    grayimg = cv2.CreateImage(cv2.GetSize(image), image.depth, 1)
    for i in range(image.height):
        for j in range(image.width):
            grayimg[i, j] = max(image[i, j][0], image[i, j][1], image[i, j][2])
#    cv.ShowImage('srcImage', image)
    cv2.ShowImage('maxGrayImage', grayimg)
def find_lines(frame, result):
    gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY)
    blur_g = cv2.bilateralFilter(gray, 9, 150, 150)
    canny = cv2.Canny(blur_g, 50, 150, apertureSize = 3)

    im2, contours, h = cv2.findContours(canny, 1, cv2.CHAIN_APPROX_SIMPLE)
    # print("contours", len(contours))
    guidingBoxes = []
    if len(contours) > 0:
        maxContour = max(contours, key=cv2.contourArea)

        # ------------------------------------------------------------------------------------------
        # ROTATE LEFT OR RIGHT OR IS_CENTERED
        min_x = -1
        max_x = -1
        for point in maxContour:
            pt = Point(point[0][0], point[0][1])
            if min_x == -1 or pt.x < min_x:
                min_x = pt.x
            if max_x == -1 or pt.x > max_x:
                max_x = pt.x

        relative_center_x = math.ceil((max_x + min_x)/2)

        width, height = cv2.GetSize(frame)
        screen_center_x = math.ceil((width)/2)

        # if it needs to be further focused
        if not about_the_same(screen_center_x, relative_center_x):
            if relative_center_x > screen_center_x:
                return "right"
            else:
                return "left"

        # ------------------------------------------------------------------------------------------
        # DISTANCE FROM GOAL

        min_y = -1
        max_y = -1
        for point in maxContour:
            pt = Point(point[0][0], point[0][1])
            if min_y == -1 or pt.y < min_y:
                min_y = pt.y
            if max_y == -1 or pt.y > max_y:
                max_y = pt.y

        size = max_y - min_y

        #actual distance  = CONSTANT_OF_AREA / size
        dist = CONSTANT_OF_AREA / size

        speed = get_speed_from_distance(dist) # need a field to test this

        # ------------------------------------------------------------------------------------------
        # JUST OUTPUT PROCESSED IMAGE

        #for contour in contours:
        approx = cv2.approxPolyDP(maxContour, 0.10 * cv2.arcLength(maxContour, True), True)
        cv2.drawContours(result, [maxContour], 0, (0, 0, 255), -1)
        cv2.imshow("DEBUG_SHAPE_FINDING", result)
Exemplo n.º 13
0
def getPolar2CartImg(image, rad):
	imgSize = cv.GetSize(image)
	c = (float(imgSize[0]/2.0), float(imgSize[1]/2.0))
	imgRes = cv.CreateImage((rad*3, int(360)), 8, 3)
	#cv.LogPolar(image,imgRes,c,50.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS)
	cv.LogPolar(image,imgRes,c,60.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS)
	return (imgRes)
Exemplo n.º 14
0
def scale_image(input, factor):
    w, h = cv2.GetSize(input)
    # print('w=' + str(w))
    # print('h=' + str(w))
    output = cv2.resize(input,
                        ((int(h) * int(factor)), (int(w) * int(factor))),
                        interpolation=cv2.INTER_CUBIC)
    return output
Exemplo n.º 15
0
 def initRecorder(self):  #Create the recorder
     codec = cv.CV_FOURCC('M', 'J', 'P', 'G')
     self.writer = cv.CreateVideoWriter(
         datetime.now().strftime("%b-%d_%H_%M_%S") + ".wmv", codec, 5,
         cv.GetSize(self.frame), 1)
     #FPS set to 5 because it seems to be the fps of my cam but should be ajusted to your needs
     self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 2,
                             8)  #Creates a font
Exemplo n.º 16
0
def weightedAverageValueGary(image):
    grayimg = cv2.CreateImage(cv2.GetSize(image), image.depth, 1)
    for i in range(image.height):
        for j in range(image.width):
            grayimg[i, j] = 0.3 * image[i, j][0] + 0.59 * image[
                i, j][1] + 0.11 * image[i, j][2]
#    cv2.ShowImage('srcImage', image)
    cv2.ShowImage('weightedGrayImage', grayimg)
Exemplo n.º 17
0
def averageValueGary(image):
    grayimg = cv2.CreateImage(cv2.GetSize(image), image.depth, 1)
    for i in range(image.height):
        for j in range(image.width):
            grayimg[i,
                    j] = (image[i, j][0] + image[i, j][1] + image[i, j][2]) / 3
#    cv2.ShowImage('srcImage', image)
    cv2.ShowImage('averageGrayImage', grayimg)
def to_gray(img):
    """
    Converts the input in grey levels
    Returns a one channel image
    """
    grey_img = cv2.CreateImage(cv2.GetSize(img), img.depth, 1)
    cv2.CvtColor(img, grey_img, cv2.CV_RGB2GRAY)

    return grey_img
Exemplo n.º 19
0
    def convert_inputs(self, img_mat, stand_size):
        img_size = cv2.GetSize(img_mat)
        img_string = img_mat.tostring()
        img = self.external_convert(img_string, img_size)

        img = tf.image.resize_bilinear(np.expand_dims(img, 0), stand_size)
        img = img / 255.0

        return img
Exemplo n.º 20
0
 def initRecorder(self):  #Create the recorder
     codec = cv.CV_FOURCC('D', 'I', 'V', 'X')
     #codec = cv.CV_FOURCC("D", "I", "B", " ")
     self.writer = cv.CreateVideoWriter(
         datetime.now().strftime("%b-%d_%H:%M:%S") + ".avi", codec, 15,
         cv.GetSize(self.frame), 1)
     #FPS set at 15 because it seems to be the fps of my cam but should be ajusted to your needs
     self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 2,
                             8)  #Creates a font
def GetListOfPixelsInPolygon(self, input_image, polygon):
    width, height = cv2.GetSize(input_image)
    arrayOfInPolygonPixels = np.empty((0, 0))
    for i in range(width):
        for j in range(height):
            point = Point(i, j)
            if (polygon.contains(point)):
                arrayOfInPolygonPixels.append(input_image[i, j, :])
    return arrayOfInPolygonPixels
 def draw_model_fitter(f):
   cv.NamedWindow("Model Fitter", cv.CV_WINDOW_AUTOSIZE)
   # Copy image
   i = cv.CreateImage(cv.GetSize(f.image), f.image.depth, 3)
   cv.Copy(f.image, i)
   for pt_num, pt in enumerate(f.shape.pts):
     # Draw normals
     cv.Circle(i, (int(pt.x), int(pt.y)), 2, (0,0,0), -1)
   cv.ShowImage("Shape Model",i)
   cv.WaitKey()
Exemplo n.º 23
0
def stream(label):  # First Video

    for image in video.iter_data():
        while app.startButton.cget("text") == "Continue":
            sleep(1)
        width, height = cv2.GetSize(image)
        img = Image.fromarray(image)
        img2 = img.resize((500, 500), Image.ANTIALIAS)
        img3 = ImageTk.PhotoImage(img2)
        label.config(image=img3)
        label.image = img3
Exemplo n.º 24
0
def display_rgb(dev, data, timestamp):
    global keep_running
    cv.Image = frame_convert.video_cv(data)
    img = cv.CreateImage(cv.GetSize(cv.Image), cv.IPL_DEPTH_16S, 3)
    cv.ShowImage('RGB', cv.Image)
    for x in range(1, 5):
        name = "img%d" % (x)
        cv.SaveImage('name.png', cv.Image)
        time.sleep(1)
    if cv.WaitKey(10) == 27:
        keep_running = False
Exemplo n.º 25
0
 def ipl2tk_image(self, iplimg):
     '''convert iplimage to PhotoImage via PIL image'''
     pil_image = Image.fromstring(
         'RGB',
         cv.GetSize(iplimg),
         iplimg.tostring(),
         'raw',
         'BGR',
         iplimg.width * 3,
         0)
     return ImageTk.PhotoImage(pil_image)
Exemplo n.º 26
0
def Bounding(binar,b):
    contours, hierarchy = cv.findContours(binar,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    if len(contours) > 0:
        cnt = max(contours, key = lambda x: cv.contourArea(x))
    else:
        return
    M = cv.moments(cnt)

    #Centroid
    cx = int(M['m10'] / M['m00'])
    cy = int(M['m01'] / M['m00'])

    #cv.rectangle(b, (cx-100, cy-100), (cx+130, cy+130), (255, 0, 0), 2)
    x, y, w, h = cv.boundingRect(cnt)
    mayor = 0
    borde = 10
    width, height = cv.GetSize(b)
    #me quedo con la dimension del rectangulo mayor
    if(w>h):
        mayor = w
    else:
        mayor = h
        #pongo el rectangulo

    # if x <= borde:
    #     xlow = 1
    # else:
    #     xlow = x-borde
    # if x + borde > width:
    #     xhigh = width
    # else:
    #     xhigh = x+borde
    # if y <= borde:
    #     ylow = 1
    # else:
    #     ylow = y-borde
    # if y + borde > height:
    #     yhigh = height
    # else:
    #     yhigh = y+borde


    # cv.rectangle(b, (xlow, ylow), (xhigh, yhigh), (0, 255, 0), 2)
    cv.rectangle(b, (x,y), (x+mayor, y+mayor), (0,255,0), 2)
    #me quedo con la mano solo
    squared = b[x:x+mayor,y:y+mayor]
    #la cambio de tamanio
    resized = cv.resize(squared,(160,160),interpolation=cv.INTER_AREA)
    return resized, b
Exemplo n.º 27
0
    def applyEffect(self, image, width, height):
        ipl_img = cv2.cv.CreateImageHeader((image.shape[1], image.shape[0]), cv.IPL_DEPTH_8U, 3)
        cv2.cv.SetData(ipl_img, image.tostring(), image.dtype.itemsize * 3 * image.shape[1])

        gray = cv.CreateImage((width, height), 8, 1)  # tuple as the first arg

        dst_img = cv.CreateImage(cv.GetSize(ipl_img), cv.IPL_DEPTH_8U, 3)  # _16S  => cv2.cv.iplimage
        if self.effect == 'dilate':
            cv.Dilate(ipl_img, dst_img, None, 5)
        elif self.effect == 'laplace':
            cv.Laplace(ipl_img, dst_img, 3)
        elif self.effect == 'smooth':
            cv.Smooth(ipl_img, dst_img, cv.CV_GAUSSIAN)
        elif self.effect == 'erode':
            cv.Erode(ipl_img, dst_img, None, 1)

        cv.Convert(dst_img, ipl_img)
        return self.ipl2tk_image(dst_img)
Exemplo n.º 28
0
def get_hands(image):
    """ Returns the hand as white on black. Uses value in HSV to determine
        hands."""
    size = cv2.GetSize(image)
    hsv = cv2.CreateImage(size, 8, 3)
    hue = cv2.CreateImage(size, 8, 1)
    sat = cv2.CreateImage(size, 8, 1)
    val = cv2.CreateImage(size, 8, 1)
    hands = cv2.CreateImage(size, 8, 1)
    cv2.Cv2tColor(image, hsv, cv2.CV2_BGR2HSV)
    cv2.Split(hsv, hue, sat, val, None)

    cv2.ShowImage('Live', image)
    cv2.ShowImage('Hue', hue)
    cv2.ShowImage('Saturation', sat)

    cv2.Threshold(
        hue, hue, 10, 255,
        cv2.CV2_THRESH_TOZERO)  #set to 0 if <= 10, otherwise leave as is
    cv2.Threshold(
        hue, hue, 244, 255,
        cv2.CV2_THRESH_TOZERO_INV)  #set to 0 if > 244, otherwise leave as is
    cv2.Threshold(hue, hue, 0, 255,
                  cv2.CV2_THRESH_BINARY_INV)  #set to 255 if = 0, otherwise 0
    cv2.Threshold(
        sat, sat, 64, 255,
        cv2.CV2_THRESH_TOZERO)  #set to 0 if <= 64, otherwise leave as is
    cv2.EqualizeHist(sat, sat)

    cv2.Threshold(sat, sat, 64, 255,
                  cv2.CV2_THRESH_BINARY)  #set to 0 if <= 64, otherwise 255

    cv2.ShowImage('Saturation threshold', sat)
    cv2.ShowImage('Hue threshold', hue)

    cv2.Mul(hue, sat, hands)

    #smooth + threshold to filter noise
    #    cv2.Smooth(hands, hands, smoothtype=cv2.CV2_GAUSSIAN, param1=13, param2=13)
    #    cv2.Threshold(hands, hands, 200, 255, cv2.CV2_THRESH_BINARY)

    cv2.ShowImage('Hands', hands)

    return hands
def meanshiftUsingILM(path):
    # Load original image given the image path
    im = cv2.LoadImageM(path)
    # Load bank of filters
    filterBank = lmfilters.loadLMFilters()
    # Resize image to decrease dimensions during clustering
    resize_factor = 1
    thumbnail = cv2.CreateMat(im.height / resize_factor,
                              im.width / resize_factor, cv2.CV_8UC3)
    cv2.Resize(im, thumbnail)
    # now work with resized thumbnail image
    response = np.zeros(shape=((thumbnail.height) * (thumbnail.width), 4),
                        dtype=float)
    for f in range(0, 48):
        filter = filterBank[f]
        # Resize the filter with the same factor for the resized image
        dst = cv2.CreateImage(cv2.GetSize(thumbnail), cv2.IPL_DEPTH_32F, 3)
        resizedFilter = cv2.CreateMat(filter.height / resize_factor,
                                      filter.width / resize_factor,
                                      filter.type)
        cv2.Resize(filter, resizedFilter)
        # Apply the current filter
        cv2.Filter2D(thumbnail, dst, resizedFilter)
        featureIndex = getFilterTypeIndex(f)
        for j in range(0, thumbnail.height):
            for i in range(0, thumbnail.width):
                # Select the max. along the three channels
                maxRes = max(dst[j, i])
                if math.isnan(maxRes):
                    maxRes = 0.0
                if maxRes > response[thumbnail.width * j + i, featureIndex]:
                    # Store the max. response for the given feature index
                    response[thumbnail.width * j + i, featureIndex] = maxRes

    # Create new mean shift instance
    ms = MeanShift(bandwidth=10, bin_seeding=True)
    # Apply the mean shift clustering algorithm
    ms.fit(response)
    labels = ms.labels_
    n_clusters_ = np.unique(labels)
    print("Number of clusters: ", len(n_clusters_))
    repaintImage(thumbnail, labels)
    cv2.Resize(thumbnail, im)
    return im
Exemplo n.º 30
0
def getPupil(frame):
	pupilImg = cv.CreateImage(cv.GetSize(frame), 8, 1)
	cv.InRangeS(frame, (30,30,30), (80,80,80), pupilImg)
	contours = cv.FindContours(pupilImg, cv.CreateMemStorage(0), mode = cv.CV_RETR_EXTERNAL)
	del pupilImg
	pupilImg = cv.CloneImage(frame)
	while contours:
		moments = cv.Moments(contours)
		area = cv.GetCentralMoment(moments,0,0)
		if (area > 50):
			pupilArea = area
			x = cv.GetSpatialMoment(moments,1,0)/area
			y = cv.GetSpatialMoment(moments,0,1)/area
			pupil = contours
			global centroid
			centroid = (int(x),int(y))
			cv.DrawContours(pupilImg, pupil, (0,0,0), (0,0,0), 2, cv.CV_FILLED)
			break
		contours = contours.h_next()
	return (pupilImg)