示例#1
0
 def draw_contour(self, contour, size):
     # create an empty one-channel image
     contour_im = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
     cv.SetZero(contour_im)  # make sure nothing is in the image
     cv.DrawContours(contour_im, contour, cv.Scalar(255), cv.Scalar(255), 0,
                     cv.CV_FILLED)
     return contour_im
    def angle(self, img):
	# extract position of red blue yellow markers
	# find distance between pairs
	# return angle from inverse cosine
	
	imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
	cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
	cv.NamedWindow("red", cv.CV_WINDOW_AUTOSIZE)
	cv.MoveWindow("red", 800, 0)
	cv.NamedWindow("blue", cv.CV_WINDOW_AUTOSIZE)
	cv.MoveWindow("blue", 800, 100)
	cv.NamedWindow("yellow", cv.CV_WINDOW_AUTOSIZE)
	cv.MoveWindow("yellow", 800, 200)
	
	dot_coords = []
	# use the corresponding thresholds for each color of marker #
	for h_low, h_high, col in [self.red_hues, self.yellow_hues, self.blue_hues]:
	    imgThresh = cv.CreateImage(cv.GetSize(img), 8, 1)
	    cv.InRangeS(imgHSV, cv.Scalar(h_low, 70, 70), cv.Scalar(h_high, 255, 255), imgThresh)
 	    moments = cv.Moments(cv.GetMat(imgThresh))
	    x_mov = cv.GetSpatialMoment(moments, 1, 0)
	    y_mov = cv.GetSpatialMoment(moments, 0, 1)
	    area = cv.GetCentralMoment(moments, 0, 0)
            small_thresh = cv.CreateImage((self.fit_camera_width, self.fit_camera_height), 8, 1)
	    cv.Resize(imgThresh, small_thresh)

	    if col == "r":
		cv.ShowImage("red", small_thresh)
	    elif col == "b":
		cv.ShowImage("blue", small_thresh)
	    elif col == "y":
		cv.ShowImage("yellow", small_thresh) 
	    if area > 0:
		posX = float(x_mov)/float(area)
	    	posY = float(y_mov)/float(area)
	    else:
		posX = 0
		posY = 0
	    dot_coords.append([posX, posY])	 
	
	r = dot_coords[0]
	y = dot_coords[1]
	b = dot_coords[2]
	# get side lengths
	y_r = self.dist(r[0], r[1], y[0], y[1])
	r_b = self.dist(b[0], b[1], r[0], r[1])
	y_b = self.dist(b[0], b[1], y[0], y[1])
	# apply law of cosines
	angle_in_rads = math.pow(y_r, 2) + math.pow(r_b, 2) - math.pow(y_b, 2)
	denom = 2.0 * y_r * r_b
	if denom > 0:
	     angle_in_rads /= 2.0 * y_r * r_b
	else:
	     angle_in_rads = 0
	rads = math.acos(angle_in_rads)
	# convert to degrees
	degs = rads * float(180.0 / math.pi)
	if degs < 0 or degs > 360: 
	     degs = 0
	return degs	
示例#3
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)				# Convert image from RGB to HSV
	imgthreshold=cv.CreateImage(cv.GetSize(im),8,1)
	cv.InRangeS(imghsv,cv.Scalar(0,100,100),cv.Scalar(20,255,255),imgthreshold)	# Select a range of yellow color
	return imgthreshold
示例#4
0
def getthresholdedimg(im):
	'''This function take RGB image.Then convert it into HSV for easy colour detection and threshold it with the given 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)
	imgthreshold=cv.CreateImage(cv.GetSize(im),8,1)
	cv.InRangeS(imghsv,cv.Scalar(h,100,10),cv.Scalar(h+20,255,255),imgthreshold)
	return imgthreshold
示例#5
0
def getthresholdedimg(im):
    imghsv = cv.CreateImage(cv.GetSize(im), 8, 3)
    cv.CvtColor(im, imghsv, cv.CV_BGR2HSV)
    imgthreshold = cv.CreateImage(cv.GetSize(im), 8, 1)
    cv.InRangeS(imghsv, cv.Scalar(h, 100, 10), cv.Scalar(h + 10, 255, 255),
                imgthreshold)
    return imgthreshold
示例#6
0
    def segmentize(self, input_img):
        histogram = self.__calculate_histogram(input_img)
        (peaks, bottoms) = find_peaks(histogram, max(histogram) / 8)

        for peak in peaks:
            if between(peak, self.expectations['table']):
                self.ranges['table'] = find_hill(histogram, peak, 0.01)
                break  #stop searching, we want the first peak since that is the highest large object.

        if not 'table' in self.ranges:
            if self.verbose:
                cv.ShowImage("histogram", self.__render_histogram(histogram))
            return None

        self.ranges['objects'] = (1, self.ranges['table'][0] - 1)

        print self.ranges

        if self.verbose:
            cv.ShowImage("histogram", self.__render_histogram(histogram))

        objects_img = create_empty_image((input_img.width, input_img.height))
        cv.SetImageROI(objects_img, cv.GetImageROI(input_img))
        cv.InRangeS(input_img, cv.Scalar(self.ranges['objects'][0]),
                    cv.Scalar(self.ranges['objects'][1]), objects_img)

        table_img = create_empty_image((input_img.width, input_img.height))
        cv.SetImageROI(table_img, cv.GetImageROI(input_img))
        cv.InRangeS(input_img, cv.Scalar(self.ranges['table'][0]),
                    cv.Scalar(self.ranges['table'][1]), table_img)

        return {'objects': objects_img, 'table': table_img}
示例#7
0
def CompositeShow(windowName, camera, image, settings, pts=[]):
    global Uncalibrated
    cv.NamedWindow(windowName)
    comp = cv.CloneImage(image)
    if (Uncalibrated):
        CalibrateCameras(comp)
        Uncalibrated = False

    if (settings.showGrid):
        #draw lines

        #p1 - p2
        cv.Line(comp, tuple(camera.calibrationmarkers[0].pos), \
                      tuple(camera.calibrationmarkers[1].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)

        #p1 - p4
        cv.Line(comp, tuple(camera.calibrationmarkers[0].pos), \
                      tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)

        #p3 - p4
        cv.Line(comp, tuple(camera.calibrationmarkers[2].pos), \
                      tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)

        #p2 - p3
        cv.Line(comp, tuple(camera.calibrationmarkers[1].pos), \
                      tuple(camera.calibrationmarkers[2].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)

    for pt in pts:
        cv.Circle(comp, (int(pt[0]), int(pt[1])), 3, cv.Scalar(255, 0, 0))
    cv.ShowImage(windowName, comp)
示例#8
0
def process_frame(frame):
	size = cv.GetSize(frame)
	hsv = cv.CreateImage(size, cv.IPL_DEPTH_8U, 3)
	cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
	
	mask = cv.CreateImage(size, 8, 1)
	cv.InRangeS(hsv, cv.Scalar(0.10*256, 0.45*256, 0.20*256, 0),
		    cv.Scalar(0.15*256, 1.00*256, 1.00*256, 0), mask);
	return mask
示例#9
0
def solve(C, Q, matches, dbsiftpath, dbimgpath):

  # open EarthMine info
  info = os.path.join(C.infodir, os.path.basename(dbimgpath)[:-4] + '.info')
  em = render_tags.EarthmineImageInfo(dbimgpath, info)
  map3d = C.pixelmap.open(dbsiftpath)

  # find non-None features
  vector = []
  for i, m in enumerate(matches):
    d = m['db']

    # get 3d pt of feature
    feature = map3d[int(d[0]), int(d[1])]
    if not feature:
      continue

    # convert from latlon to meters relative to earthmine camera
    pz, px = geom.lltom(em.lat, em.lon, feature['lat'], feature['lon'])
    py = feature['alt'] - em.alt
    vector.append((m['query'][:2], (px, py, -pz)))

  print vector[0]

  # reference camera matrix
  # f 0 0
  # 0 f 0
  # 0 0 1
  A = cv.CreateMat(3, 3, cv.CV_64F)
  cv.SetZero(A)
  f = 662 # focal len?
  cv.Set2D(A, 0, 0, cv.Scalar(f))
  cv.Set2D(A, 1, 1, cv.Scalar(f))
  cv.Set2D(A, 2, 2, cv.Scalar(1))

  # convert vector to to cvMats
  objectPoints3d = cv.CreateMat(len(vector), 1, cv.CV_64FC3)
  imagePoints2d = cv.CreateMat(len(vector), 1, cv.CV_64FC2)
  for i, (p2d, p3d) in enumerate(vector):
    cv.Set2D(imagePoints2d, i, 0, cv.Scalar(*p2d))
    cv.Set2D(objectPoints3d, i, 0, cv.Scalar(*p3d))

  coeff = cv.CreateMat(4, 1, cv.CV_64F)
  rvec = cv.CreateMat(3, 1, cv.CV_64F)
  tvec = cv.CreateMat(3, 1, cv.CV_64F)
  cv.SetZero(coeff)
  cv.SetZero(rvec)
  cv.SetZero(tvec)

  # since rvec, tvec are zero the initial guess is the earthmine camera
  ret = cv.FindExtrinsicCameraParams2(objectPoints3d, imagePoints2d, A,
    coeff, rvec, tvec, useExtrinsicGuess=False)
  np_rvec = np.matrix(rvec)
  np_tvec = np.matrix(tvec)
  print np_rvec
  print np_tvec
  return np_rvec, np_tvec
示例#10
0
def GetYellowThresholded(img):
    # Convert the image into an HSV image
    imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
    cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
    imgThreshed = cv.CreateImage(cv.GetSize(img), 8, 1)
    # Ranges specified for YELLOW colour filtering, keeping in mind the deviations.
    cv.InRangeS(imgHSV, cv.Scalar(45, 130, 50), cv.Scalar(65, 230, 150),
                imgThreshed)  #<<<-----------------set color value here
    return imgThreshed
示例#11
0
def blob_statistics(binary_image,
                    max_area=99999.0,
                    max_dim=99999.0):  #, show=False):
    statistics = []
    storage = cv.CreateMemStorage(0)
    #FindContours(image,        storage, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE, offset=(0, 0))
    contours = cv.FindContours(binary_image, storage, cv.CV_RETR_TREE,
                               cv.CV_CHAIN_APPROX_SIMPLE, (0, 0))
    #number_contours, contours = cv.FindContours(binary_image, storage, cv.sizeof_CvContour, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE, (0,0))
    #TODO: FIGURE OUT WHAT THE EQUIV OF SIZEOF IS IN OPENCV2
    #import pdb
    #pdb.set_trace()

    original_ptr = contours
    while contours != None:
        try:
            bx, by, bwidth, bheight = cv.BoundingRect(contours, 0)
            bounding_rect = Rect(bx, by, bwidth, bheight)
            moments = cv.Moments(contours, 0)
            #area = moments.m00
            #approximation to area since cvMoments' area seem broken
            area = bounding_rect.width * bounding_rect.height
            if False:
                #TODO NOT WORKING!!
                if moments.m00 == 0.0:
                    centroid = (bounding_rect.x, bounding_rect.y)
                else:
                    centroid = (moments.m10 / moments.m00,
                                moments.m01 / moments.m00)
            else:
                if bwidth > 0:
                    cx = bx + bwidth / 2.
                else:
                    cx = bx

                if bheight > 0:
                    cy = by + bheight / 2.
                else:
                    cy = by
                centroid = (cx, cy)
                #if show:
                #    print 'areas is', area, bounding_rect.width, bounding_rect.height
                if area > max_area or bounding_rect.width > max_dim or bounding_rect.height > max_dim:
                    cv.DrawContours(binary_image, contours, cv.Scalar(0),
                                    cv.Scalar(0), 0, cv.CV_FILLED)
                else:
                    stats = {
                        'area': area,
                        'centroid': centroid,
                        'rect': bounding_rect
                    }
                    statistics.append(stats)
                contours = contours.h_next()
        except Exception, e:
            pass
            #This is due to OPENCV BUG and not being able to see inside contour object'
            break
示例#12
0
def GetRedThresholded(img):
    # Convert the image into an HSV image
    imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
    cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
    imgThreshed = cv.CreateImage(cv.GetSize(img), 8, 1)
    # Ranges specified for RED colour filtering, keeping in mind the deviations.
    cv.InRangeS(imgHSV, cv.Scalar(15, 200, 180), cv.Scalar(35, 255, 245),
                imgThreshed)  #<<<-----------------set color value here
    return imgThreshed
示例#13
0
def draw_blobs(frame, blobs, classification_window_width):
    if frame.nChannels == 1:
        color = cv.Scalar(200)
    else:
        color = cv.Scalar(255, 0, 0)

    for b in blobs:
        rect = blob_to_rect(b, classification_window_width)
        if rect != None:
            cv.Rectangle(frame, rect.top_left(), rect.bottom_right(), color, 1)
def thresholded_image(image):
    # convert image to hsv
    image_hsv = cv.CreateImage(cv.GetSize(image), image.depth, 3)
    cv.CvtColor(image, image_hsv, cv.CV_BGR2HSV)
    # threshold the image (note--I am tracking a blue ball, not a yellow one)
    image_threshed = cv.CreateImage(cv.GetSize(image), image.depth, 1)
    blue_min = cv.Scalar(70, 110, 120)
    blue_max = cv.Scalar(105, 255, 255)
    cv.InRangeS(image_hsv, blue_min, blue_max, image_threshed)
    return image_threshed
示例#15
0
def FPV_thread():
    global camera_index
    global capture
    global WINDOW_NAME
    global latest_frame
    global FPV_thread_stop
    global overlay_message  # shared with application return results
    global face_position    # shared with application return results

    FPV_init()

    cv.NamedWindow(WINDOW_NAME, cv.CV_WINDOW_NORMAL)
    cv.MoveWindow(WINDOW_NAME, 0, 0)

    width_scale = 1.0
    height_scale = 1.0
    while True:
        frame = cv.QueryFrame(capture)
        cv.Flip(frame, None, 1)

        #copy to buffer
        frame_lock.acquire()
        original_imagesize = (0,0)
        resized_imagesize = (0,0)
        if not latest_frame:
            latest_frame = cv.CreateImage((640, 480), frame.depth, frame.nChannels)
            original_imagesize = cv.GetSize(frame)
            resized_imagesize = cv.GetSize(latest_frame)
            width_scale = original_imagesize[0]*1.0/resized_imagesize[0]
            height_scale = original_imagesize[1]*1.0/resized_imagesize[1]
        cv.Resize(frame, latest_frame)
        frame_lock.release()


        #Display Result
        text_start_point = (10, 50)
        cv.PutText(frame, overlay_message, text_start_point, font, cv.Scalar(255,255,255))
        cv.Rectangle(frame, text_start_point, (original_imagesize[0], 100), cv.Scalar(0,0,0), thickness=cv.CV_FILLED)
        if face_position[0] > 0.0:
            point1 = (int(face_position[0]*width_scale), int(face_position[1]*height_scale))
            point2 = (int((face_position[0] + face_position[2])*width_scale), \
                    int((face_position[1]+face_position[3])*height_scale))
            cv.Rectangle(frame, point1, point2, \
                    cv.Scalar(255, 255, 255), thickness=2)
        cv.ShowImage(WINDOW_NAME, frame)
        cv.ResizeWindow(WINDOW_NAME, 200, 100)
        cv.NamedWindow(WINDOW_NAME, cv.CV_WINDOW_NORMAL);
        cv.SetWindowProperty(WINDOW_NAME, 0, cv.CV_WINDOW_FULLSCREEN);
        c = cv.WaitKey(10)
        if c == ord('q'):
            break

    print "[INFO] FPV Thread is finished"
    FPV_thread_stop = True
    FPV_close()
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
示例#17
0
def thresholded_image(image):
    # convert image to hsv
    image_hsv = cv.CreateImage(cv.GetSize(image), image.depth, 3)
    cv.CvtColor(image, image_hsv, cv.CV_BGR2HSV)
    # threshold the image (note--I am tracking a blue ball, not a yellow one)
    image_threshed = cv.CreateImage(cv.GetSize(image), image.depth, 1)
    orange_min = cv.Scalar(0, 100, 150)
    orange_max = cv.Scalar(255, 200, 255)
#    blue_min = cv.Scalar(255, 200, 160) #orange
#    blue_max = cv.Scalar(255, 111, 0) #orange
    cv.InRangeS(image_hsv, orange_min, orange_max, image_threshed)
    return image_threshed
示例#18
0
文件: gui.py 项目: sdp-2011/sdp-9
    def drawHistogram(self, image):
        w = 0.5
        n = 9
        gauss1d = np.exp(-0.5 * w / n * np.array(range(-(n - 1), n, 2))**2)
        gauss1d /= sum(gauss1d)

        hist_size = 180
        hist = cv.CreateHist([hist_size], cv.CV_HIST_ARRAY, [[0, 256]], 1)
        cv.CvtColor(image, self.HSV, cv.CV_BGR2HSV)
        cv.Split(self.HSV, self.B, self.G, self.R, None)

        channels = self.B, self.G, self.R
        _red = cv.Scalar(255, 0, 0, 0)
        _green = cv.Scalar(0, 255, 0, 0)
        _blue = cv.Scalar(0, 0, 255, 0)
        _white = cv.Scalar(255, 255, 255, 0)
        _trans = cv.Scalar(0, 0, 0, 255)
        values = _blue, _green, _red

        positions = (0, (self.Ihist.height + 10), 2 * self.Ihist.height + 20)

        for ch, colour, Y in zip(channels, values, positions):
            cv.CalcHist([ch], hist, 0, None)
            cv.Set(self.Ihist, _trans)
            bin_w = cv.Round(float(self.Ihist.width) / hist_size)
            # min_value, max_value, pmin, pmax = cv.GetMinMaxHistValue(hist)

            X = self.HSV.width - self.Ihist.width
            rect = (X, Y, self.Ihist.width, self.Ihist.height)

            hist_arr = [cv.GetReal1D(hist.bins, i) for i in range(hist_size)]
            hist_arr = np.convolve(gauss1d, hist_arr, 'same')

            cv.SetImageROI(image, rect)
            hist_arr *= self.Ihist.height / max(hist_arr)
            for i, v in enumerate(hist_arr):
                cv.Rectangle(self.Ihist, (i * bin_w, self.Ihist.height),
                             ((i + 1) * bin_w, self.Ihist.height - round(v)),
                             colour, -1, 8, 0)

            diffs = np.diff(hist_arr, 1)
            for i, v in enumerate(diffs):
                if v > 1 and diffs[i - 1] * diffs[i] <= 0:
                    cv.Rectangle(self.Ihist, (i * bin_w, self.Ihist.height),
                                 ((i + 1) * bin_w,
                                  self.Ihist.height - round(hist_arr[i])),
                                 _white, -1, 8, 0)

            cv.AddWeighted(image, 1 - self.hist_visibility, self.Ihist,
                           self.hist_visibility, 0.0, image)

        cv.ResetImageROI(image)
示例#19
0
def GetThresholdedImage(img):
    # Convert the image into an HSV image
    imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
    cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)

    imgThreshed = cv.CreateImage(cv.GetSize(img), 8, 1)

    # Values 20,100,100 to 30,255,255 working perfect for yellow at around 6pm
    #	cv.InRangeS(imgHSV, cv.Scalar(112, 100, 100), cv.Scalar(124, 255, 255), imgThreshed)

    cv.InRangeS(imgHSV, cv.Scalar(20, 130, 200), cv.Scalar(40, 200, 255),
                imgThreshed)
    return imgThreshed
def createModelsfromStats():
    cv.ConvertScale(IavgF, IavgF, float(1.0 / Icount))
    cv.ConvertScale(IdiffF, IdiffF, float(1.0 / Icount))

    cv.AddS(IdiffF, cv.Scalar(1.0, 1.0, 1.0), IdiffF)
    setHighThresh(10.0)
    setLowThresh(10.0)
示例#21
0
 def mouse_cb(event, x, y, flags, param):
     if (event == cv.CV_EVENT_LBUTTONUP):
         print x * scale, y * scale
         pt = (x, y)
         cv.Circle(map_image, pt, int(38 / scale), cv.Scalar(255, 0, 0), -1)
         cv.ShowImage("map", map_image)
     pass
示例#22
0
def image_call():
    global FilterWindowName
    ret, cv_image = cap.retrieve()
    if (ret):
        filtered = FindBall(cv_image)
        cv2.imshow(FilterWindowName, filtered)
        mcs = PickBlob(filtered)
        for mc in mcs:
            cv2.circle(cv_image, (int(mc[0]), int(mc[1])), 3,
                       cv.Scalar(255, 0, 0))
        #cv_image = cv2.cvtColor(cv_image, cv.CV_BGR2RGB)
        cvIm = cv.CreateImageHeader((cv_image.shape[1], cv_image.shape[0]),
                                    cv.IPL_DEPTH_8U, 3)
        cv.SetData(cvIm, cv_image.tostring(),
                   cv_image.dtype.itemsize * 3 * cv_image.shape[1])
        CompositeShow("Image window", cam1, cvIm, settings)
        #correct the frame
        tosend = []
        for mc in mcs:
            new = cam1.FrameCorrect(mc[0], mc[1])

            rectified = unit2world(new)

            #print "Ball: ", str(mc), " -> ", str(new)
            #print "Ball: ", str(mc), " -> ", str(rectified)
            tosend.append(rectified)

        #now send it!
        tcpc.send(tosend)

        cv.WaitKey(3)
示例#23
0
def random_color(random):
    """
    Return a random color
    """
    icolor = random.randint(0, 0xFFFFFF)
    return cv.Scalar(icolor & 0xff, (icolor >> 8) & 0xff,
                     (icolor >> 16) & 0xff)
示例#24
0
def plot_color_rectangle(image, mask):
    a = screen_height
    width = 180
    height = 256
    #print (width, height)
    color_rectangle = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 3)
    (image_width, image_height) = cv.GetSize(cv.fromarray(image))
    #print (image_width, image_height)
    rectangle = (((0, 0), (width, 0), (width, height), (0, height)), BLACK)
    cv.FillConvexPoly(color_rectangle, *rectangle)
    converted_image = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
    for i in range(image_height):
        for j in range(image_width):
            if mask == None or mask[i][j]:
                color = image[i][j]
                hls = converted_image[i][j]
                #print color
                (h, l, s) = hls
                hls = (h, l, s)
                #print hls
                x = int(h)
                y = int(l)
                color = cv.Scalar(*color)
                rectangle = (((x, y), (x, y), (x, y), (x, y)), color)
                cv.FillConvexPoly(color_rectangle, *rectangle)
    #x = (a - 1) / 2
    #y = (a - 1) / 2
    #white_dot = (x, y)
    #rectangle = ((white_dot, white_dot, white_dot, white_dot), WHITE)
    cv.FillConvexPoly(color_rectangle, *rectangle)
    return color_rectangle
示例#25
0
    def createModelsfromStats(self):
        cv.ConvertScale(self.IavgF, self.IavgF, float(1.0 / self.Icount))
        cv.ConvertScale(self.IdiffF, self.IdiffF, float(1.0 / self.Icount))

        cv.AddS(self.IdiffF, cv.Scalar(1.0, 1.0, 1.0), self.IdiffF)
        self.setHighThresh(200.0)
        self.setLowThresh(200.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)				# Convert image from RGB to HSV
		
	# A little change here. Creates images for blue and yellow (or whatever color you like).
	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
示例#27
0
    def set_bounds(self):

        def clamp(x, m, M):
            if x < m: return m
            if x > M: return M
            return x

        def clamp256(v): return clamp(v, 0, 0xFF)

        self.lower = cv.Scalar(
                clamp256(self.hue_target - self.hue_tolerance),
                clamp256(self.sat_target - self.sat_tolerance),
                clamp256(self.val_target - self.val_tolerance))
        self.upper = cv.Scalar(
                clamp256(self.hue_target + self.hue_tolerance),
                clamp256(self.sat_target + self.sat_tolerance),
                clamp256(self.val_target + self.val_tolerance))
示例#28
0
 def __init__(self, im, title=None):
     assert im.nChannels == 3
     self.title = title
     ims = image.split(im)
     if self.title is None:
         self.title = "Histogram-" + str(id(im)) + "-"
     self.histograms = (
         HistogramWindow(ims[0],
                         self.title + "red",
                         color=cv.Scalar(255, 0, 0)),
         HistogramWindow(ims[1],
                         self.title + "green",
                         color=cv.Scalar(0, 255, 0)),
         HistogramWindow(ims[2],
                         self.title + "blue",
                         color=cv.Scalar(0, 0, 255)),
     )
示例#29
0
 def getThreshold(self, image):
     #http://www.aishack.in/2010/07/tracking-colored-objects-in-opencv/
     #http://nashruddin.com/OpenCV_Region_of_Interest_(ROI)
     img = cv.LoadImage(image)
     imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
     cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
     # Since our pink/red values are from h=0-20 and h=160-179, we have to do thresholding in
     # two steps...maybe there is an easier way...
     imgThreshed1 = cv.CreateImage(cv.GetSize(img), 8, 1)
     imgThreshed2 = cv.CreateImage(cv.GetSize(img), 8, 1)
     cv.InRangeS(imgHSV, cv.Scalar(0, 50, 50), cv.Scalar(20, 255, 255),
                 imgThreshed1)
     cv.InRangeS(imgHSV, cv.Scalar(160, 50, 50), cv.Scalar(179, 255, 255),
                 imgThreshed2)
     imgThreshed = cv.CreateImage(cv.GetSize(img), 8, 1)
     cv.Or(imgThreshed1, imgThreshed2, imgThreshed)
     return imgThreshed
示例#30
0
def show3(img, depth):
    image = img[:, :, ::-1]  #RGB -> BGR We reverse the colour array
    point = np.unravel_index(depth.argmin(),
                             depth.shape)  # Get closest point to camera
    image = cv.fromarray(image.astype(np.uint8))
    cv.Circle(image, point[::-1], 20, cv.Scalar(255, 0, 0),
              -1)  # Add a circle in pointer
    cv.ShowImage('rgb', image)