Пример #1
0
def avgstd_image_list(images):
    mean = None
    std = None
    if len(images) > 0:
        scale = 1. / len(images)
        mean = cv.CreateImage(cv.GetSize(images[0]), cv.IPL_DEPTH_32F,
                              images[0].channels)
        std = cv.CreateImage(cv.GetSize(images[0]), cv.IPL_DEPTH_32F,
                             images[0].channels)
        buf = cv.CreateImage(cv.GetSize(images[0]), cv.IPL_DEPTH_32F,
                             images[0].channels)
        for image in images:
            cv.Add(image, mean, mean)
            cv.Mul(image, image, buf)
            cv.Add(buf, std, std)
        cv.ConvertScale(mean, mean, scale)
        cv.ConvertScale(std, std, scale)
        cv.Mul(mean, mean, buf)
        cv.Sub(std, buf, std)
        cv.Pow(std, std, 0.5)

        meanresult = cv.CreateImage(cv.GetSize(images[0]), images[0].depth,
                                    images[0].channels)
        stdresult = cv.CreateImage(cv.GetSize(images[0]), images[0].depth,
                                   images[0].channels)
        cv.ConvertScale(mean, meanresult)
        cv.ConvertScale(std, stdresult)
        del buf
        del std
        del mean
    return (meanresult, stdresult)
Пример #2
0
def anaglyph(left_color, right_color, correction):
    #create oversized image
    #result = cv.CreateImage(cv.GetSize(right_color), cv.IPL_DEPTH_8U, 4)
    w, h = cv.GetSize(left_color)
    bgra = cv.CreateImage((w * 2, h), cv.IPL_DEPTH_8U, 4)
    cv.Set(bgra, 0)
    right_bgra = add_alpha_channel(right_color,
                                   round(255 / 2.))  #cyan (remove red?)
    left_bgra = add_alpha_channel(left_color,
                                  round(255 / 2.))  #red (remove blue?, green?)

    #remove blue & green from left => red
    left_red = remove_channels(left_bgra, [0, 1])
    #remove red from right_bgra => cyan
    right_cyan = remove_channels(right_bgra, [2])

    if correction < 0:
        left_area = cv.GetSubRect(bgra, (-correction, 0, w, h))
        right_area = cv.GetSubRect(bgra, (0, 0, w, h))
        valid_area = cv.GetSubRect(bgra, (-correction, 0, w + correction, h))
    else:
        #copy left & right onto bgra
        left_area = cv.GetSubRect(bgra, (0, 0, w, h))
        right_area = cv.GetSubRect(bgra, (correction, 0, w, h))
        valid_area = cv.GetSubRect(bgra, (correction, 0, w - correction, h))

    cv.Add(left_red, left_area, left_area)
    cv.Add(right_cyan, right_area, right_area)

    #return right_cyan
    #return left_red
    #return left_bgra
    #return bgra
    return valid_area
Пример #3
0
def get_normalized_rgb_planes(r, g, b):
    size = cv.GetSize(r)
    #    r,g,b = get_three_planes(img)

    nr_plane = cv.CreateImage(size, 8, 1)
    ng_plane = cv.CreateImage(size, 8, 1)
    nb_plane = cv.CreateImage(size, 8, 1)

    r32 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
    g32 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
    b32 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
    sum = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
    cv.Zero(sum)
    cv.Convert(r, r32)
    cv.Convert(g, g32)
    cv.Convert(b, b32)

    cv.Add(r32, g32, sum)
    cv.Add(b32, sum, sum)

    tmp = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
    cv.Div(r32, sum, tmp)
    cv.ConvertScale(tmp, nr_plane, scale=255)
    cv.Div(g32, sum, tmp)
    cv.ConvertScale(tmp, ng_plane, scale=255)
    cv.Div(b32, sum, tmp)
    cv.ConvertScale(tmp, nb_plane, scale=255)

    #    res = image_empty_clone(img)
    #    cv.Merge(nr_plane,ng_plane,nb_plane,None,res)
    return nr_plane, ng_plane, nb_plane
Пример #4
0
def concat_images(a, b):
    img_height = max(a.height, b.height)
    c = cv.CreateImage((a.width+b.width, img_height), a.depth, a.channels)
    a_area = cv.GetSubRect(c, (0,0, a.width, a.height))
    b_area = cv.GetSubRect(c, (a.width, 0, b.width, b.height))
    cv.Add(a, a_area, a_area)
    cv.Add(b, b_area, b_area)
    return c
def getthresholdedimgRGeneric(R, imhsv):		
	# A little change here. Creates images for blue and yellow (or whatever color you like).
	imgRed =cv.CreateImage(cv.GetSize(imhsv),8,1)
	imgBlue=cv.CreateImage(cv.GetSize(imhsv),8,1)
	imgGreen=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	imgthreshold=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	cv.InRangeS(imghsv,cv.Scalar(R["minRed"][0], R["minRed"][1], R["minRed"][2]),cv.Scalar(R["maxRed"][0], R["maxRed"][1], R["maxRed"][2]),imgRed)	# Select a range of yellow color
	cv.InRangeS(imghsv,cv.Scalar(R["minBlue"][0], R["minBlue"][1], R["minBlue"][2]),cv.Scalar(R["maxBlue"][0], R["maxBlue"][1], R["maxBlue"][2]),imgBlue)	# Select a range of blue color
	cv.InRangeS(imghsv,cv.Scalar(R["minGreen"][0], R["minGreen"][1], R["minGreen"][2]),cv.Scalar(R["maxGreen"][0], R["maxGreen"][1], R["maxGreen"][2]),imgGreen)	# Select a range of blue color
	
	cv.Add(imgRed,imgBlue,imgthreshold)
	cv.Add(imgGreen, imgGreen, imgthreshold)
	return imgthreshold
def getthresholdedimgR4(imhsv):		
	# A little change here. Creates images for blue and yellow (or whatever color you like).
	imgRed =cv.CreateImage(cv.GetSize(imhsv),8,1)
	imgBlue=cv.CreateImage(cv.GetSize(imhsv),8,1)
	imgGreen=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	imgthreshold=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	cv.InRangeS(imghsv,cv.Scalar(169, 168, 115),cv.Scalar(180, 243, 200),imgRed)	# Select a range of yellow color
	cv.InRangeS(imghsv,cv.Scalar(100,100,100),cv.Scalar(120,255,255),imgBlue)	# Select a range of blue color
	cv.InRangeS(imghsv,cv.Scalar(67, 103, 46),cv.Scalar(100, 209, 184),imgGreen)	# Select a range of blue color
	
	cv.Add(imgRed,imgBlue,imgthreshold)
	cv.Add(imgGreen, imgGreen, imgthreshold)
	return imgthreshold
Пример #7
0
    def findRectPoints(self, oldRectPoints):
        hueRange = self.hueRange
        satRange = self.satRange
        valRange = self.valRange
        clone = cv.CloneImage(self.frame)
        hsv = cv.CloneImage(self.channels3)
        threshold = cv.CloneImage(self.channels1)
        threshold2 = cv.CloneImage(self.channels1)

        cv.Smooth(clone, clone, cv.CV_GAUSSIAN, 7, 7)

        cv.CvtColor(clone, hsv, cv.CV_BGR2HSV)
        cv.InRangeS(hsv, (hueRange[0], satRange[0], valRange[0]),
                    (hueRange[1], satRange[1], satRange[1]), threshold)
        cv.InRangeS(hsv, (hueRange[2], satRange[0], satRange[0]),
                    (hueRange[3], satRange[1], valRange[1]), threshold2)
        cv.Add(threshold, threshold2, threshold)
        cv.Erode(threshold, threshold, iterations=5)
        cv.Dilate(threshold, threshold, iterations=5)

        #       cv.ShowImage(self.color, threshold)

        memory = cv.CreateMemStorage(0)
        clone2 = cv.CloneImage(threshold)
        contours = cv.FindContours(clone2, memory, cv.CV_RETR_LIST,
                                   cv.CV_CHAIN_APPROX_SIMPLE, (0, 0))
        if not contours:
            rectPoints = oldRectPoints
        else:
            rectPoints = cv.BoundingRect(list(contours))
        return rectPoints
Пример #8
0
	def CountPinkPixels(self,cv_img):
                cv.Smooth(cv_img, cv_img, cv.CV_BLUR, 3);

	        hsv_img = cv.CreateImage(cv.GetSize(cv_img), 8, 3)
	        cv.CvtColor(cv_img, hsv_img, cv.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 
            	thresholded_img =  cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
            	cv.InRangeS(hsv_img, (120, 80, 80), (180, 255, 255), thresholded_img)
		#print type(thresholded_img)
		mat = cv.GetMat(thresholded_img)
		#mat = hsv_img.getNumpy()
		(width,height) = cv.GetSize(thresholded_img)
		aveW = 0
		aveH = 0
		count = 0
		for j in range(0,height):			
			for i in range(0,width):
				if (mat[j,i] == 255.0):
					count += 1
					aveH += j 
					aveW += i
					print i,j, mat[j,i]
		
		aveH = aveH/count
		aveW = aveW/count
		
		overlay = cv.CreateImage(cv.GetSize(cv_img),8,3)
		cv.Circle(overlay, (int(aveW), int(aveH)), 2, (255,255,255),20)
		cv.Add(cv_img,overlay,cv_img)
		return cv_img
Пример #9
0
def main():
    root = "/Users/soswow/Documents/Face Detection/test/negative"
    #    root = "/Users/soswow/Documents/Face Detection/test/sets/negative"
    #    root = "/Users/soswow/Documents/Face Detection/test/edge_view/positive"
    #    root = "/Users/soswow/Documents/Face Detection/test/sobel/positive"
    #    root = "/Users/soswow/Documents/Face Detection/test/sets/positive"
    #    root = "/Users/soswow/Documents/Face Detection/test/falses"

    for folder in os.listdir(root):
        path = p.join(root, folder)
        if p.isdir(path):
            sum = cv.CreateMat(32, 32, cv.CV_32F)
            cv.Zero(sum)
            k = 0
            for path, _ in directory_files(path):
                try:
                    img = cv.LoadImage(path, iscolor=False)
                except IOError:
                    continue
                mat = cv.CreateMat(32, 32, cv.CV_32F)
                cv.Zero(mat)
                cv.Convert(cv.GetMat(img), mat)
                cv.Add(mat, sum, sum)
                k += 1
            avg = cv.CreateMat(32, 32, cv.CV_32F)
            cv.Zero(avg)
            count = cv.CreateMat(32, 32, cv.CV_32F)
            cv.Zero(count)
            cv.Set(count, k)
            cv.Div(sum, count, avg)
            new_img = cv.CreateImage((32, 32), 8, 0)
            cv.Zero(new_img)
            cv.Convert(avg, new_img)
            cv.SaveImage(p.join(root, "%s-avg.png" % folder), new_img)
Пример #10
0
    def draw(self, img, pixmapper):
        '''draw the icon on the image'''

        if self.trail is not None:
            self.trail.draw(img, pixmapper)

        icon = self.img()
        (px, py) = pixmapper(self.latlon)

        # find top left
        px -= icon.width / 2
        py -= icon.height / 2
        w = icon.width
        h = icon.height

        (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img)

        cv.SetImageROI(icon, (sx, sy, w, h))
        cv.SetImageROI(img, (px, py, w, h))
        cv.Add(icon, img, img)
        cv.ResetImageROI(img)
        cv.ResetImageROI(icon)

        # remember where we placed it for clicked()
        self.posx = px + w / 2
        self.posy = py + h / 2
Пример #11
0
def hsv_orange_red_threshold(input_image):
    blur_image = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC3)
    cv.Smooth(input_image, blur_image, cv.CV_BLUR, 10, 10)
    proc_image = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC3)
    cv.CvtColor(blur_image, proc_image, cv.CV_BGR2HSV)
    split_image = [
        cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1),
        cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1),
        cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1)
    ]
    cv.Split(proc_image, split_image[0], split_image[1], split_image[2], None)

    thresh_0 = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1)
    thresh_1 = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1)
    thresh_2 = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1)
    red_orange = cv.CreateMat(input_image.rows, input_image.cols, cv.CV_8UC1)
    cv.Threshold(split_image[1], thresh_0, 128, 255,
                 cv.CV_THRESH_BINARY)  # > 50% saturation
    cv.Threshold(split_image[0], thresh_1, 220, 255,
                 cv.CV_THRESH_BINARY)  # > Purple
    cv.Threshold(split_image[0], thresh_2, 10, 255,
                 cv.CV_THRESH_BINARY_INV)  # < Yellow-Orange
    cv.Add(thresh_1, thresh_2, red_orange)
    cv.And(red_orange, thresh_0, red_orange)

    return red_orange
Пример #12
0
    def findRectPoints(self, oldRectPoints):
        hueRange = self.hueRange
        clone = cv.CloneImage(self.frame)
        hsv = cv.CloneImage(self.channels3)
        threshold = cv.CloneImage(self.channels1)
        threshold2 = cv.CloneImage(self.channels1)

        cv.CvtColor(clone, hsv, cv.CV_RGB2HSV)

        cv.InRangeS(hsv, (165, 100, 100), (180, 255, 255), threshold)
        cv.InRangeS(hsv, (0, 100, 100), (15, 255, 255), threshold2)
        cv.Add(threshold, threshold2, threshold)
        self.hue += 1
        print self.hue
        cv.Erode(threshold, threshold, iterations=5)
        cv.Dilate(threshold, threshold, iterations=5)

        cv.ShowImage(self.color, threshold)

        memory = cv.CreateMemStorage(0)
        clone2 = cv.CloneImage(threshold)
        contours = cv.FindContours(clone2, memory, cv.CV_RETR_LIST,
                                   cv.CV_CHAIN_APPROX_SIMPLE, (0, 0))
        if not contours:
            rectPoints = oldRectPoints
        else:
            rectPoints = cv.BoundingRect(contours)
        return rectPoints
    def getAverageValues2(self, images):
        """ get the average values over all the images
            for every two images, divides the images by 2
            then adds them together
        """

        if len(images) == 0:
            return None
        if len(images) == 1:
            return images[0]

        width = images[0].width
        height = images[0].height
        # create image with only 2's
        # this will be used for division
        divisionImage = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)
        cv.Set(divisionImage, 2)
        image1 = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)
        image2 = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)

        avgImage = cv.CloneImage(images[0])
        for image in images:
            # divide images by 2
            cv.Div(avgImage, divisionImage, image1)
            cv.Div(image, divisionImage, image2)

            # add them to get result
            cv.Add(image1, image2, avgImage)

        return avgImage
Пример #14
0
    def locateMarker(self, frame):
        self.frameReal = cv.CloneImage(frame)
        self.frameImag = cv.CloneImage(frame)
        self.frameRealThirdHarmonics = cv.CloneImage(frame)
        self.frameImagThirdHarmonics = cv.CloneImage(frame)

        # Calculate convolution and determine response strength.
        cv.Filter2D(self.frameReal, self.frameReal, self.matReal)
        cv.Filter2D(self.frameImag, self.frameImag, self.matImag)
        cv.Mul(self.frameReal, self.frameReal, self.frameRealSq)
        cv.Mul(self.frameImag, self.frameImag, self.frameImagSq)
        cv.Add(self.frameRealSq, self.frameImagSq, self.frameSumSq)

        # Calculate convolution of third harmonics for quality estimation.
        cv.Filter2D(self.frameRealThirdHarmonics, self.frameRealThirdHarmonics,
                    self.matRealThirdHarmonics)
        cv.Filter2D(self.frameImagThirdHarmonics, self.frameImagThirdHarmonics,
                    self.matImagThirdHarmonics)

        min_val, max_val, min_loc, max_loc = cv.MinMaxLoc(self.frameSumSq)
        self.lastMarkerLocation = max_loc
        (xm, ym) = max_loc
        self.determineMarkerOrientation(frame)
        self.determineMarkerQuality()
        return max_loc
Пример #15
0
def detect_and_draw(img):
    t1 = time.time()

    # allocate temporary images
    gray = cv.CreateImage((img.width, img.height), 8, 1)
    small_img = cv.CreateImage((cv.Round(
        img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1)

    # blur the source image to reduce color noise
    cv.Smooth(img, img, cv.CV_BLUR, 3)
    hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3)
    cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)
    thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
    #cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img)

    # White
    sensitivity = 15
    cv.InRangeS(hsv_img, (0, 0, 255 - sensitivity), (255, sensitivity, 255),
                thresholded_img)

    # Red
    #cv.InRangeS(hsv_img, (0, 150, 0), (5, 255, 255), thresholded_img)

    # Blue
    #cv.InRangeS(hsv_img, (100, 50, 50), (140, 255, 255), thresholded_img)

    # Green
    #cv.InRangeS(hsv_img, (40, 50, 50), (80, 255, 255), thresholded_img)

    mat = cv.GetMat(thresholded_img)
    moments = cv.Moments(mat, 0)
    area = cv.GetCentralMoment(moments, 0, 0)

    # scale input image for faster processing
    cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)

    cv.EqualizeHist(small_img, small_img)

    if (area > 5000):
        #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 = cv.GetSpatialMoment(moments, 1, 0) / area
        y = cv.GetSpatialMoment(moments, 0, 1) / area
        x = int(round(x))
        y = int(round(y))

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

        cv.Circle(overlay, (x, y), 2, (0, 0, 0), 20)
        cv.Add(img, overlay, img)
        #add the thresholded image back to the img so we can see what was
        #left after it was applied
        #cv.Merge(thresholded_img, None, None, None, img)
        t2 = time.time()
        message = "Color tracked!"
        print "detection time = %gs x=%d,y=%d" % (round(t2 - t1, 3), x, y)

    cv.ShowImage("Color detection", img)
Пример #16
0
def edge_threshold(image, roi=None, debug=0):
    thresholded = cv.CloneImage(image)
    horizontal = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_16S, 1)
    magnitude32f = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_32F, 1)
    vertical = cv.CloneImage(horizontal)
    v_edge = cv.CloneImage(image)
    magnitude = cv.CloneImage(horizontal)

    storage = cv.CreateMemStorage(0)
    mag = cv.CloneImage(image)
    cv.Sobel(image, horizontal, 0, 1, 1)
    cv.Sobel(image, vertical, 1, 0, 1)
    cv.Pow(horizontal, horizontal, 2)
    cv.Pow(vertical, vertical, 2)

    cv.Add(vertical, horizontal, magnitude)
    cv.Convert(magnitude, magnitude32f)
    cv.Pow(magnitude32f, magnitude32f, 0.5)
    cv.Convert(magnitude32f, mag)
    if roi:
        cv.And(mag, roi, mag)
    cv.Normalize(mag, mag, 0, 255, cv.CV_MINMAX, None)
    cv.Threshold(mag, mag, 122, 255, cv.CV_THRESH_BINARY)
    draw_image = cv.CloneImage(image)
    and_image = cv.CloneImage(image)
    results = []

    threshold_start = 17
    for window_size in range(threshold_start, threshold_start + 1, 1):
        r = 20
        for threshold in range(0, r):
            cv.AdaptiveThreshold(image, thresholded, 255, \
                cv.CV_ADAPTIVE_THRESH_MEAN_C, cv.CV_THRESH_BINARY_INV, window_size, threshold)
            contour_image = cv.CloneImage(thresholded)
            contours = cv.FindContours(contour_image, storage, cv.CV_RETR_LIST)
            cv.Zero(draw_image)
            cv.DrawContours(draw_image, contours, (255, 255, 255),
                            (255, 255, 255), 1, 1)
            if roi:
                cv.And(draw_image, roi, draw_image)
            cv.And(draw_image, mag, and_image)
            m1 = np.asarray(cv.GetMat(draw_image))
            m2 = np.asarray(cv.GetMat(mag))
            total = mag.width * mag.height  #cv.Sum(draw_image)[0]

            coverage = cv.Sum(and_image)[0] / (mag.width * mag.height)
            if debug:
                print threshold, coverage
                cv.ShowImage("main", draw_image)
                cv.ShowImage("main2", thresholded)
                cv.WaitKey(0)
            results.append((coverage, threshold, window_size))

    results.sort(lambda x, y: cmp(y, x))
    _, threshold, window_size = results[0]
    cv.AdaptiveThreshold(image, thresholded, 255, cv.CV_ADAPTIVE_THRESH_MEAN_C, \
        cv.CV_THRESH_BINARY, window_size, threshold)

    return thresholded
Пример #17
0
 def __add__(self, addend):
     """Add two images together -> cvImg
     """
     bmp = self.empty()
     if isinstance(addend, Img):
         cv.Add(self.cv_rep(), addend.cv_rep(), bmp)
     else:
         cv.AddS(self.cv_rep(), cv.Scalar(addend, addend, addend), bmp)
     return bmp
Пример #18
0
def getthresholdedimg(im):
    '''this function take RGB image.Then convert it into HSV for easy colour detection and threshold it with yellow part as white and all other regions as black.Then return that image'''
    imghsv=cv.CreateImage(cv.GetSize(im),8,3)
    cv.CvtColor(im,imghsv,cv.CV_BGR2HSV)#CV_BGR2HSV# Convert image from RGB to HSV

    # A little change here. Creates images for green,blue and yellow (or whatever color you like).
    imgyellow=cv.CreateImage(cv.GetSize(im),8,1)
    imgblue=cv.CreateImage(cv.GetSize(im),8,1)
    imggreen=cv.CreateImage(cv.GetSize(im),8,1)
    imgthreshold=cv.CreateImage(cv.GetSize(im),8,1)

    cv.InRangeS(imghsv,cv.Scalar(85,100,100),cv.Scalar(95,255,255),imggreen)
    cv.InRangeS(imghsv,cv.Scalar(20,100,100),cv.Scalar(30,255,255),imgyellow)#imgyellow# Select a range of yellow color
    cv.InRangeS(imghsv,cv.Scalar(100,100,100),cv.Scalar(120,255,255),imgblue)#imgblue# Select a range of blue color
    # Add everything
    cv.Add(imgyellow,imgblue,imgthreshold)
    cv.Add(imgthreshold,imggreen,imgthreshold)
    return imgthreshold
Пример #19
0
def getthresholdedimg(imhsv):	
	#Get component colors
	imgyellow=cv.CreateImage(cv.GetSize(imhsv),8,1)
	imgblue=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	imgthreshold=cv.CreateImage(cv.GetSize(imhsv),8,1)
	
	cv.InRangeS(imghsv,cv.Scalar(20,100,100),cv.Scalar(30,255,255),imgyellow)	# Select a range of yellow color
	cv.InRangeS(imghsv,cv.Scalar(100,100,100),cv.Scalar(120,255,255),imgblue)	# Select a range of blue color
	cv.Add(imgyellow,imgblue,imgthreshold)
	return imgthreshold
Пример #20
0
    def drawPointOnImage(self,img,object_position):
        try:
            object_indicator = cv.CreateImage(cv.GetSize(img), img.depth, 3)
            cv.Circle(object_indicator, object_position, 12, (0,0,255), 4)
            cv.Add(img, object_indicator, img)
        except:
            pass
#            object_indicator = cv.CreateImage(cv.GetSize(img), img.depth, 1)
#            cv.Circle(object_indicator, object_position, 12, (0), 4)
#            cv.Add(img, object_indicator, img)
        return img
Пример #21
0
def main():
    color_tracker_window = "output"
    thresh_window = "thresh"
    capture = cv.CaptureFromCAM(-1)
    cv.NamedWindow(color_tracker_window, 1)
    cv.NamedWindow(thresh_window, 1)
    imgScrible = None
    global posX
    global posY

    fido.init_servos()

    while True:
        frame = cv.QueryFrame(capture)
        cv.Smooth(frame, frame, cv.CV_BLUR, 3)

        if (imgScrible is None):
            imgScrible = cv.CreateImage(cv.GetSize(frame), 8, 3)

        imgThresh = GetThresholdedImage(frame)

        mat = cv.GetMat(imgThresh)
        #Calculating the moments
        moments = cv.Moments(mat, 0)
        area = cv.GetCentralMoment(moments, 0, 0)
        moment10 = cv.GetSpatialMoment(moments, 1, 0)
        moment01 = cv.GetSpatialMoment(moments, 0, 1)

        #lastX and lastY stores the previous positions
        lastX = posX
        lastY = posY
        #Finding a big enough blob
        if (area > 100000):

            #Calculating the coordinate postition of the centroid
            posX = int(moment10 / area)
            posY = int(moment01 / area)

            print 'x: ' + str(posX) + ' y: ' + str(posY) + ' area: ' + str(
                area)
            #drawing lines to track the movement of the blob
            if (lastX > 0 and lastY > 0 and posX > 0 and posY > 0):
                cv.Line(imgScrible, (posX, posY), (lastX, lastY),
                        cv.Scalar(0, 255, 255), 5)
            #Adds the three layers and stores it in the frame
            #frame -> it has the camera stream
            #imgScrible -> it has the line tracking the movement of the blob
            cv.Add(frame, imgScrible, frame)

        cv.ShowImage(thresh_window, imgThresh)
        cv.ShowImage(color_tracker_window, frame)
        c = cv.WaitKey(10)
        if (c != -1):
            break
Пример #22
0
def addGaussianNoise(image_path, save_path):
    img = cv.LoadImage(image_path)
    noise = cv.CreateImage(cv.GetSize(img), img.depth, img.nChannels)
    cv.SetZero(noise)
    rng = cv.RNG(-1)
    cv.RandArr(rng, noise, cv.CV_RAND_NORMAL, cv.ScalarAll(0),
               cv.ScalarAll(25))
    cv.Add(img, noise, img)
    tempName = os.path.splitext(
        os.path.basename(image_path))[0] + "_noised.jpg"
    save_image = os.path.join(save_path, tempName)
    cv.SaveImage(save_image, img)
Пример #23
0
 def run(self): 
     while True: 
         img = cv.QueryFrame( self.capture ) 
                     
         #blur the source image to reduce color noise 
         cv.Smooth(img, img, cv.CV_BLUR, 3); 
         
         #convert the image to hsv(Hue, Saturation, Value) so its  
         #easier to determine the color to track(hue) 
         hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3) 
         cv.CvtColor(img, hsv_img, cv.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 
         thresholded_img =  cv.CreateImage(cv.GetSize(hsv_img), 8, 1) 
         cv.InRangeS(hsv_img, (115, 75, 75), (135, 255, 255), thresholded_img) 
         
         #determine the objects moments and check that the area is large  
         #enough to be our object 
         thresholded_img2 = cv.GetMat(thresholded_img)
         moments = cv.Moments(thresholded_img2,0) 
         area = cv.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 = cv.GetSpatialMoment(moments, 1, 0)/area 
             y = cv.GetSpatialMoment(moments, 0, 1)/area 
         
             # print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area) 
             
             
             x = int(x)
             y = int(y)
             
             #create an overlay to mark the center of the tracked object 
             overlay = cv.CreateImage(cv.GetSize(img), 8, 3) 
             
             cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20) 
             cv.Add(img, overlay, img) 
             #add the thresholded image back to the img so we can see what was  
             #left after it was applied 
             cv.Merge(thresholded_img, None, None, None, img) 
          
         #display the image  
         cv.ShowImage(color_tracker_window, img) 
         
         if cv.WaitKey(10) == 27: 
             break 
Пример #24
0
def cam_measurebulk(nframes=100,
                    interactive=True,
                    show=True,
                    norm=False,
                    verb=0):
    """
	Take **nframes** frames and average these. If **norm** is set, set the 
	average of the summed frame to unity, otherwise it is divided by the 
	number of frames.

	This routine is intended to measure flat and dark frames. Flat frames 
	might be normalized such that dividing by these does not affect the 
	average intensity of the input frame. Dark frames should never be 
	normalized.

	The flatfield is stored in CAM_CFG['flat'] and is used automatically 
	from then on.

	@param [in] nframes Number of frames to average
	@param [in] show Show flat field + one correct image when done
	@param [in] verb Verbosity
	@return Summed and scaled frame.
	"""

    if (verb & VERB_M > L_INFO):
        print "Measuring bulk (n=%d)..." % (nframes)

    if (interactive):
        print "Will measure bulk now, press c to continue..."
        while (True):
            cam_getimage(show=True, waitkey=0)
            if (chr(cv.WaitKey(1) & 255) == "c"):
                print "ok!"
                break

    bulkimg = cam_getimage(show=False, dfcorr=False, raw=True)

    for dummy in xrange(nframes - 1):
        cv.Add(bulkimg, cam_getimage(show=False, dfcorr=False, raw=True),
               bulkimg)

    if (norm):
        cv.ConvertScale(bulkimg, bulkimg, scale=1.0 / cv.Avg(bulkimg)[0])
    else:
        cv.ConvertScale(bulkimg, bulkimg, scale=1.0 / nframes)

    if (show):
        cv.NamedWindow("cam_bulkimg", cv.CV_WINDOW_AUTOSIZE)
        cv.ShowImage('cam_bulkimg', bulkimg)
        c = cv.WaitKey(20)

    return bulkimg
Пример #25
0
def max_contrast(image):
    """Maximise the contrast of an image using top and bottom hat filters."""
    size = cv.GetSize(image)
    bh = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
    th = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
    s1 = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
    s2 = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
    el = cv.CreateStructuringElementEx(3, 3, 1, 1, cv.CV_SHAPE_ELLIPSE)
    cv.MorphologyEx(image, th, None, el, cv.CV_MOP_TOPHAT, 1)
    cv.MorphologyEx(image, bh, None, el, cv.CV_MOP_BLACKHAT, 1)
    cv.Add(image, th, s1)
    cv.Sub(s1, bh, s2)
    return s2
Пример #26
0
	def crunch():
		size = cv.GetSize(band3)
		assert size == cv.GetSize(band4)
		numerator = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
		cv.Sub(band4, band3, numerator)
		denominator = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
		cv.Add(band4, band3, denominator)
		ndvi_img = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
		cv.Div(numerator, denominator, ndvi_img)

		# (NDVI + 1)
		cv.AddS(ndvi_img, 1, ndvi_img)
		return ndvi_img
Пример #27
0
def average_image_list(images):
    result = None
    if len(images) > 0:
        scale = 1. / len(images)
        mean = cv.CreateImage(cv.GetSize(images[0]), cv.IPL_DEPTH_32F,
                              images[0].channels)
        result = cv.CreateImage(cv.GetSize(images[0]), images[0].depth,
                                images[0].channels)
        for image in images:
            cv.Add(image, mean, mean)
        cv.ConvertScale(mean, mean, scale)
        cv.ConvertScale(mean, result)
        del mean
    return result
Пример #28
0
def image_processor():
    cv.Smooth(gray_image, gray_image, cv.CV_GAUSSIAN, 3,
              3)  #Blurring to remove some noise
    cv.AbsDiff(prev_image, gray_image,
               accumulator)  #Getting the difference image
    cv.InRangeS(accumulator, threshold_limit1_lower, threshold_limit1_upper,
                accumulator)  #Thresholding the difference image
    cv.Dilate(accumulator, accumulator, None,
              2)  #Dilating the thresholded difference image
    cv.Add(accumulator, sum_image, sum_image,
           accumulator)  #Adding the image to a register to use fading
    cv.SubS(sum_image, fading_factor, sum_image)  #Fading
    cv.InRangeS(sum_image, threshold_limit2_lower, threshold_limit2_upper,
                accumulator)  #Thresholding the fading image
    cv.Copy(gray_image, prev_image)
    cv.Copy(accumulator, temp_image)
Пример #29
0
def edge_magnitude(image):
    magnitude32f = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_32F, 1)
    horizontal = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_16S, 1)
    vertical = cv.CloneImage(horizontal)
    magnitude = cv.CloneImage(horizontal)

    mag = cv.CloneImage(image)
    cv.Sobel(image, horizontal, 0, 1, 1)
    cv.Sobel(image, vertical, 1, 0, 1)
    cv.Pow(horizontal, horizontal, 2)
    cv.Pow(vertical, vertical, 2)

    cv.Add(vertical, horizontal, magnitude)
    cv.Convert(magnitude, magnitude32f)
    cv.Pow(magnitude32f, magnitude32f, 0.5)
    cv.Convert(magnitude32f, mag)
    return mag
Пример #30
0
def getthresholdedimg(im):
    '''this function take RGB image.Then convert it into HSV for easy colour detection and threshold it with yellow and blue part as white and all other regions as black.Then return that image'''
    global imghsv
    imghsv = cv.CreateImage(cv.GetSize(im), 8, 3)
    cv.CvtColor(im, imghsv, cv.CV_BGR2HSV)

    imgyellow = cv.CreateImage(cv.GetSize(im), 8, 1)
    imgblue = cv.CreateImage(cv.GetSize(im), 8, 1)

    imgthreshold = cv.CreateImage(cv.GetSize(im), 8, 1)

    cv.InRangeS(imghsv, cv.Scalar(20, 100, 100), cv.Scalar(30, 255, 255),
                imgyellow)  # Select a range of yellow color
    cv.InRangeS(imghsv, cv.Scalar(100, 100, 100), cv.Scalar(120, 255, 255),
                imgblue)  # Select a range of blue color
    cv.Add(imgyellow, imgblue, imgthreshold)
    return imgthreshold