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) # Convert image from RGB to HSV cv.CvtColor(im,imghsv,cv.CV_BGR2HSV) # creates images for blue imgblue = cv.CreateImage(cv.GetSize(im),8,1) # creates blank image to which color images are added imgthreshold = cv.CreateImage(cv.GetSize(im),8,1) # determine HSV color thresholds for yellow, blue, and green # cv.InRange(src, lowerbound, upperbound, dst) # for imgblue, lowerbound is 95, and upperbound is 115 cv.InRangeS(imghsv, cv.Scalar(55,100,100), cv.Scalar(155,255,255), imgblue) #55/155 original, 105 seems to be lower threshold needed to eliminate flag detection # add color thresholds to blank 'threshold' image cv.Add(imgthreshold, imgblue, imgthreshold) return imgthreshold
def getthresholdedimg(im): #this fucntion takes the RGB image. Then converts it into HSV for easy color detection and thresholds it with yellow part 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(20,100,100),cv.Scalar(30,255,255),imgthreshold) return imgthreshold
def getthresholdedimg(im): 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(23, 100, 100), cv.Scalar(25, 255, 255), imgthreshold) ## catch the orange yellow blob return imgthreshold
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(20, 100, 100), cv.Scalar(30, 255, 255), imgthreshold) # Select a range of yellow color return imgthreshold
def thresholdImage(img): # allocate temp image based on size of input img img_hsv = cv.CreateImage((img.width, img.height), 8, 3) # 3 channel img_thresh = cv.CreateImage((img.width, img.height), 8, 1) # 1 channel cv.CvtColor(img, img_hsv, cv.CV_BGR2HSV) cv.InRangeS(img_hsv, cv.Scalar(0, 100, 100), cv.Scalar(43, 255, 255), img_thresh) return (img_thresh)
def ColorProcess(img): # returns thresholded image imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3) # converts BGR image to HSV cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV) imgProcessed = cv.CreateImage(cv.GetSize(img), 8, 1) # converts the pixel values lying within the range to 255 and stores it in the destination cv.InRangeS(imgHSV, (100, 94, 84), (109, 171, 143), imgProcessed) return imgProcessed
def getThresholdImage(im): newim = cv.CloneImage(im) cv.Smooth(newim, newim, cv.CV_BLUR, 12) #Remove noise hsv = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(newim, hsv, cv.CV_BGR2HSV) # Convert image to HSV imThreshed = cv.CreateImage(cv.GetSize(im), 8, 1) #Do the threshold on the hsv image, with the right range for the yellow color cv.InRangeS(hsv, cv.Scalar(20, 100, 100), cv.Scalar(30, 255, 255), imThreshed) del hsv return imThreshed
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) imggreen = cv.CreateImage(cv.GetSize(im),8,1) # glen added this 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 in HSV, where 20 is low H and 30 is high H 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(150,100,100), cv.Scalar(170,255,255), imggreen ) # glen added this; select a range of green color cv.Add(imgthreshold, imgyellow, imgthreshold) cv.Add(imgthreshold, imgblue, imgthreshold) cv.Add(imgthreshold, imggreen, imgthreshold) return imgthreshold
def getContour(cvImg): lowerBound = cv.Scalar(0, 0, 0) upperBound = cv.Scalar(3, 3, 3) size = cv.GetSize(cvImg) output = cv.CreateMat(size[0], size[1], cv.CV_8UC1) cv.InRangeS(cvImg, lowerBound, upperBound, output) storage = cv.CreateMemStorage(0) seq = cv.FindContours(output, storage, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE) mask = np.array(output) y, x = np.nonzero(mask) return (x, y)
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, (120, 80, 80), (140, 255, 255), thresholded_img) #determine the objects moments and check that the area is large #enough to be our object moments = cv.Moments(cv.GetMat(thresholded_img), 0) area = cv.GetCentralMoment(moments, 0, 0) #there can be noise in the video so ignore objects with small areas if (area > 10000): #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) #create an overlay to mark the center of the tracked object overlay = cv.CreateImage(cv.GetSize(img), 8, 3) cv.Circle(overlay, (int(x), int(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
def calibrate(self, img, mask_range = (50, 100)): # mask: ignore pixels that are really close or far away, like the # Nao (close, low values) and kinect noise (far far away, high values) _, _, width, height = cv.GetImageROI(img) mask = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1) cv.InRangeS(img, mask_range[0], mask_range[1], mask) # using the mask, create a new image containing only the pixels of # interest. self.base_img = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1) cv.SetImageROI(self.base_img, cv.GetImageROI(img)) # get the minimum value, and subtract that from all pixels so only # the difference in depth in the image remains. minimum, _, _, _ = cv.MinMaxLoc(img, mask) cv.SubS(img, minimum, self.base_img)
def centerRadius(cvImg, ColorLower=None, ColorUpper=None): lowerBound = cv.Scalar(90, 0, 90) upperBound = cv.Scalar(171, 80, 171) size = cv.GetSize(cvImg) output = cv.CreateMat(size[0], size[1], cv.CV_8UC1) cv.InRangeS(cvImg, lowerBound, upperBound, output) yi, xi = np.nonzero(output) #points = np.array([xi,yi]).T #coords = [tuple(points[pt]) for pt in range(len(points))] coords = zip(xi, yi) PointArray2D32f = cv.CreateMat(1, len(coords), cv.CV_32FC2) for (i, (x, y)) in enumerate(coords): PointArray2D32f[0, i] = (x, y) (center, size, angle) = cv.FitEllipse2(PointArray2D32f) h, k = center radius = np.sqrt(np.power((xi[0] - h), 2) + np.power(yi[0] - k, 2)) return tuple(np.around([h, k])), round(radius)
def findImage(img): #Set up storage for images frame_size = cv.GetSize(img) img2 = cv.CreateImage(frame_size,8,3) tmp = cv.CreateImage(frame_size,8,cv.CV_8U) h = cv.CreateImage(frame_size,8,1) #copy original image to do work on cv.Copy(img,img2) #altering the image a bit for smoother processing cv.Smooth(img2,img2,cv.CV_BLUR,3) cv.CvtColor(img2,img2,cv.CV_BGR2HSV) #make sure temp is empty cv.Zero(tmp) #detection based on HSV value #30,100,90 lower limit on pic 41,255,255 on pic #cv.InRangeS(img2,cv.Scalar(25,100,87),cv.Scalar(50,255,255),tmp) #Range for green plate dot in my Living room #cv.InRangeS(img2,cv.Scalar(55,80,60),cv.Scalar(65,95,90),tmp) #classroom #cv.InRangeS(img2,cv.Scalar(55,80,60),cv.Scalar(70,110,70),tmp) #Kutztowns Gym cv.InRangeS(img2,cv.Scalar(65,100,112),cv.Scalar(85,107,143),tmp) elmt_shape=cv.CV_SHAPE_ELLIPSE pos = 3 element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, elmt_shape) cv.Dilate(tmp,tmp,element,6) cv.Erode(tmp,tmp,element,2) cv.Split(tmp,h,None,None,None) storage = cv.CreateMemStorage() scan = sc.FindContours(h,storage) xyImage=drawCircles(scan,img) if xyImage != None: return (xyImage,tmp) else: return None
def colorFilter(img, color, calibrate): imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV) if color == "yellow": minColor = cv.Scalar(20, 70, 70) maxColor = cv.Scalar(60, 255, 255) elif color == "blue": minColor = cv.Scalar(100, 100, 100) maxColor = cv.Scalar(120, 255, 255) elif color == "calibrate": minColor = cv.Scalar(calibrate[0], calibrate[1], calibrate[2]) maxColor = minColor imgFiltered = cv.CreateImage(cv.GetSize(img), 8, 1) cv.InRangeS(imgHSV, minColor, maxColor, imgFiltered) return imgFiltered
#capture the current frame frame = cv.QueryFrame(capture) if frame is None: break # mirror cv.Flip(frame, None, 1) originalImage = frame hsvImage = cv.CreateImage(cv.GetSize(originalImage), 8, 3) cv.CvtColor(originalImage, hsvImage, cv.CV_BGR2HSV) thresholdImage = cv.CreateImage(cv.GetSize(originalImage), 8, 1) cv.InRangeS(hsvImage, cv.Scalar(20.74, 75, 75), cv.Scalar(30.74, 255, 255), thresholdImage) thresholdImageArray = np.asarray(cv.GetMat(thresholdImage)) thresholdImageArray = cv2.GaussianBlur(thresholdImageArray, (0, 0), 2) thresholdImage = cv.fromarray(thresholdImageArray) circles = cv2.HoughCircles(thresholdImageArray, cv.CV_HOUGH_GRADIENT, 2, 10, param1=40, param2=80, minRadius=4, maxRadius=1500)
if not frame: cv.WaitKey(0) break cv.Smooth(frame, frame, cv.CV_BLUR, 3) hsv = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, hsv, cv.CV_BGR2HSV) thr = cv.CreateImage(cv.GetSize(frame), 8, 1) #Change threshold value cv.InRangeS(hsv, (0, 140, 10), (170, 180, 60), thr) moments = cv.Moments(cv.GetMat(thr, 1), 0) area = cv.GetCentralMoment(moments, 0, 0) cv.Line(frame, (80, 0), (80, 120), (0, 0, 255), 3, 8, 0) if (area > 10000): x = cv.GetSpatialMoment(moments, 1, 0) / area y = cv.GetSpatialMoment(moments, 0, 1) / area # overlay = cv.CreateImage(cv.GetSize(frame),8,3) cv.Circle(frame, (int(x), int(y)), 2, (255, 255, 255), 20)
import cv2.cv as cv import time capture = cv.CaptureFromCAM(0) cv.SetCaptureProperty(capture, 3, 640) cv.SetCaptureProperty(capture, 4, 480) while True: img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR, 3) hue_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hue_img, cv.CV_BGR2HSV) threshold_img=cv.CreateImage(cv.GetSize(hue_img), \ 8,1) cv.InRangeS(hue_img,(0,150,0),(5,255,255), \ threshold_img) storage = cv.CreateMemStorage(0) contour = cv.FindContours \ (threshold_img,storage, \ cv.CV_RETR_CCOMP, \ cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: rect = cv.BoundingRect(list(contour)) if rect[0]>157.00 and rect[0]<216.83 and \ rect[1]>227.00 and rect[1]<336.67: print('a') if rect[0]>216.83 and rect[0]<276.66 and \ rect[1]>227.00 and rect[1]<336.67: print('b') if rect[0]>276.66 and rect[0]<336.49 and \ rect[1]>227.00 and rect[1]<336.67:
#height = 120 #leave None for auto-detection width = 640 #leave None for auto-detection height = 480 #leave None for auto-detection middle_w = 2 #Cross Center width 十字中心歸零校正,數字越大線往左 middle_h = 2 #Cross Center height 十字中心歸零校正,數字越大線往上 cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, width) cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height) while True: img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR, 3) hue_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hue_img, cv.CV_BGR2HSV) threshold_img = cv.CreateImage(cv.GetSize(hue_img), 8, 1) cv.InRangeS(hue_img, (38, 120, 60), (75, 255, 255), threshold_img) storage = cv.CreateMemStorage(0) contour = cv.FindContours(threshold_img, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: rect = cv.BoundingRect(list(contour)) contour = contour.h_next() size = (rect[2] * rect[3]) if size > 100: pt1 = (rect[0], rect[1]) pt2 = (rect[0] + rect[2], rect[1] + rect[3]) cv.Rectangle(img, pt1, pt2, cv.CV_RGB(255, 0, 0), 3) ######################################## contour center ####################################################
# cv.Zero(hsv) # cv.Zero(diff2) # print time.clock() # img1 = cv.LoadImage(CreateImg(cap1, 'capture')) # cv.ShowImage('img1', img1) # cv.WaitKey() # img2 = cv.LoadImage(CreateImg(cap1, 'capture')) # cv.ShowImage('img2', img2) cv.Sub(img1, img2, diff) path = u"img/sub{}.jpg".format(datetime.strftime( datetime.now(), "%S%f ")) # Уникальное имя для каждого кадра cv.SaveImage(path, diff) cv.CvtColor(diff, hsv, cv2.COLOR_BGR2HSV) lower_wite = cv.Scalar(50, 50, 50) uper_wite = cv.Scalar(255, 255, 255) frame_threshed = cv.CreateImage(cv.GetSize(hsv), 8, 1) cv.InRangeS(hsv, lower_wite, uper_wite, frame_threshed) path = u"img/mask{}.jpg".format(datetime.strftime( datetime.now(), "%S%f ")) # Уникальное имя для каждого кадра cv.SaveImage(path, frame_threshed) cv.Copy(img2, diff2, frame_threshed) cv.ShowImage('capture', diff2) path = u"img/fin{}.jpg".format(datetime.strftime( datetime.now(), "%S%f ")) # Уникальное имя для каждого кадра cv.SaveImage(path, diff2)
capture = cv.CaptureFromCAM(0) img_size = cv.GetSize(cv.QueryFrame(capture)) source = cv.CreateImage(img_size, 8, 3) hsv_img = cv.CreateImage(img_size, 8, 3) hsv_mask = cv.CreateImage(img_size, 8, 1) hsv_min = cv.Scalar(0, 30, 80, 0) hsv_max = cv.Scalar(20, 150, 255, 0) while True: src = cv.QueryFrame(capture) cv.NamedWindow("src", 1) cv.ShowImage("src", src) cv.CvtColor(src, hsv_img, cv.CV_BGR2HSV) cv.NamedWindow("hsv-img", 1) cv.ShowImage("hsv-img", hsv_img) cv.InRangeS(hsv_img, hsv_min, hsv_max, hsv_mask) cv.NamedWindow("hsv-msk", 1) cv.ShowImage("hsv-msk", hsv_mask) # hsv_mask.origin = 1 c = cv.WaitKey(10) if c == 27: #exit break elif c == 13: #save the image to a file cv.SaveImage('runtime/image.jpg', src) break
def findBrightObjects(self): cv.NamedWindow("camera") while True : frame = cv.QueryFrame(self.video1) # print type(frame) [rows, cols] = cv.GetSize(frame) # image = cv.CreateMat(rows, cols, cv.CV_8UC3) image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, frame.nChannels) cv.Copy(frame, image) # image = cv.GetMat(frame) cv.ShowImage("camera", image) # grayScaleFullImage = cv.CreateImage((image.width, image.height), 8, 1) # cv.CvtColor(image, grayScaleFullImage, cv.CV_BGR2GRAY) # convert to hsv hsvImage = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, frame.nChannels) cv.CvtColor(image, hsvImage, cv.CV_BGR2HSV) cv.ShowImage("hsv", hsvImage) # hsvImage = cv2.cvtColor(imageArray, cv.CV_BGR2HSV) # h_plane = cv.CreateImage(cv.GetSize(image), 8, 1) # s_plane = cv.CreateImage(cv.GetSize(image), 8, 1) # v_plane = cv.CreateImage(cv.GetSize(image), 8, 1) # Split HSV into two of it's three channels. V channel is same as greyscale image so ignore. # cv.Split(hsvImage, h_plane, s_plane, v_plane, None) # http://robbierickman.blogspot.co.uk/2011/11/laserduckpy-coloured-object-tracking.html # planes = [h_plane, s_plane] # # h_bins = 30 # s_bins = 32 # hist_size = [h_bins, s_bins] # # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */ # h_ranges = [0, 180] # # saturation varies from 0 (black-gray-white) to # # 255 (pure spectrum color) # s_ranges = [0, 255] # ranges = [h_ranges, s_ranges] # scale = 10 # hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1) # cv.CalcHist([cv.GetImage(i) for i in planes], hist) # (_, max_value, _, _) = cv.GetMinMaxHistValue(hist) # # hist_img = cv.CreateImage((h_bins*scale, s_bins*scale), 8, 3) # # for h in range(h_bins): # for s in range(s_bins): # bin_val = cv.QueryHistValue_2D(hist, h, s) # intensity = cv.Round(bin_val * 255 / max_value) # cv.Rectangle(hist_img, # (h*scale, s*scale), # ((h+1)*scale - 1, (s+1)*scale - 1), # cv.RGB(intensity, intensity, intensity), # cv.CV_FILLED) # http://uvhar.googlecode.com/hg/test/laser_tracker.py # Threshold ranges of HSV components. # cv.InRangeS(h_plane, hmin, hmax, h_plane) # # cv.InRangeS(s_plane, smin, smax, s_plane) # # cv.InRangeS(v_plane, vmin, vmax, v_plane) # # finalImage = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) # # # Perform an AND on HSV components to identify the laser! # cv.And(h_plane, s_plane, finalImage) # # This actually Worked OK for me without using Saturation. # # cv.cvAnd(laser_img, s_img,laser_img) # # # Merge the HSV components back together. # cv.Merge(h_plane, s_plane, v_plane, None, hsvImage) # cv.ShowImage("hue", h_plane) # cv.ShowImage("saturation", s_plane) # cv.ShowImage("value", v_plane) thresholdImage = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) cv.InRangeS(hsvImage, cv.Scalar(0, 100, 100), cv.Scalar(50, 255, 255), thresholdImage) # thresholdImage = cv2.threshold(hsvImage, [0, 100, 100], [50, 255, 255], cv2.THRESH_BINARY) cv.ShowImage("threshold image", thresholdImage) # remove noise from threshold image kernel = cv.CreateStructuringElementEx(9, 9, 5, 5, cv.CV_SHAPE_CROSS) # Dilate- replaces pixel value with highest value pixel in kernel cv.Dilate(thresholdImage, thresholdImage, kernel, 2) # Erode- replaces pixel value with lowest value pixel in kernel cv.Erode(thresholdImage, thresholdImage, kernel, 2) # element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) # cv.Dilate(thresholdImage, element, thresholdImage) # cv2.erode(thresholdImage, element, thresholdImage) cv.ShowImage("cleaned image ", thresholdImage) # contour detection imageArray = np.asarray(cv.GetMat(thresholdImage), np.uint8, 1) print type(imageArray) imageArray = imageArray.T # contours, hier = cv2.findContours(imageArray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # print "TYPE " + str(type(contours)) + " " + str(len(contours)) # # # for i in contours: # # print i # maxArea = -1 # contourIndex = -1 # if contours: # for i in range(0, len(contours)): # cnt = contours[i].astype('int') # print type(cnt) # area = cv2.contourArea(cnt) # print area # if area > maxArea: # maxArea = area # contourIndex = i # # if contourIndex != -1: # cv2.drawContours(imageArray, contours, contourIndex, (0, 0 , 255), 10) params = cv2.SimpleBlobDetector_Params() # params.minDistBetweenBlobs = 1.0 # minimum 10 pixels between blobs # params.filterByArea = True # filter my blobs by area of blob # params.minArea = 5.0 # min 20 pixels squared # params.maxArea = 500.0 # max 500 pixels squared params.minDistBetweenBlobs = 50.0 params.filterByInertia = False params.filterByConvexity = False params.filterByColor = False params.filterByCircularity = False params.filterByArea = True params.minArea = 20.0 params.maxArea = 500.0 myBlobDetector = cv2.SimpleBlobDetector(params) keypoints = myBlobDetector.detect(imageArray) print "blobs " + str(keypoints) # extract the x y coordinates of the keypoints: for i in range(0, len(keypoints) - 1): print keypoints[i].pt pt1 = (int(keypoints[i].pt[0]), int(keypoints[i].pt[1])) pt2 = (int(keypoints[i + 1].pt[0]), int(keypoints[i + 1].pt[1])) cv2.line(imageArray, pt1, pt2, (255, 0, 0)) # float X=keypoints[i].pt.x; # float Y=keypoints[i].pt.y; cv2.imshow("final detection ", imageArray) # if cv.WaitKey(10) == 27: break
width = 640 #leave None for auto-detection height = 480 #leave None for auto-detection middle_w = 2 #Cross Center width 十字中心歸零校正,數字越大線往左 middle_h = 2 #Cross Center height 十字中心歸零校正,數字越大線往上 cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,width) cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,height) while True: img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR,3) hue_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hue_img, cv.CV_BGR2HSV) threshold_img = cv.CreateImage(cv.GetSize(hue_img), 8, 1) #Python: cv.InRangeS(src, lower, upper, dst) http://www.colorspire.com/ cv.InRangeS(hue_img, (38,120,60), (75,255,255), threshold_img) # color code green #cv.InRangeS(hue_img, (100,120,60), (200,255,255), threshold_img) # color code blue #cv.InRangeS(hue_img, (0,100,60), (10,255,255), threshold_img) # color code red storage = cv.CreateMemStorage(0) contour = cv.FindContours(threshold_img, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: rect = cv.BoundingRect(list(contour)) contour = contour.h_next() size = (rect[2] * rect[3]) if size > 100: pt1 = (rect[0], rect[1]) pt2 = (rect[0] + rect[2], rect[1] + rect[3]) cv.Rectangle(img, pt1, pt2, cv.CV_RGB(255,0,0), 3)
def run(self): initialTime = 0. #sets the initial time num_Frames = int( cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_COUNT)) fps = cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_FPS) for ii in range(num_Frames - 8): print('Frame: ' + str(ii) + ' of ' + str(num_Frames)) # read the ii-th frame 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 # It's 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 the is 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) # uncomment below for tracking blue # cv.InRangeS(hsv_img, (112, 50, 50), (118, 200, 200), thresholded_img) # tracking red cv.InRangeS(hsv_img, (160, 150, 100), (180, 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 > 2500): #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 elapsedTime = ii / fps f.write( str(elapsedTime) + ',' + '%013.9f' % x + ',' + '%013.9f' % y + "\n" ) #prints output to the specified output file for later use # # 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) # close the data file f.close()
def findBlob(rgbimage, hsvimage, maskimage, blobimage, hsvcolorrange, hsvmin, hsvmax): cv.CvtColor(rgbimage, hsvimage, cv.CV_BGR2HSV) hsvmin = [ hsvmin[0] - hsvcolorrange[0], hsvmin[1] - hsvcolorrange[1], hsvmin[2] - hsvcolorrange[2] ] hsvmax = [ hsvmax[0] + hsvcolorrange[0], hsvmax[1] + hsvcolorrange[1], hsvmax[2] + hsvcolorrange[2] ] if hsvmin[0] < 0: hsvmin[0] = 0 if hsvmin[1] < 0: hsvmin[1] = 0 if hsvmin[2] < 0: hsvmin[2] = 0 if hsvmax[0] > 255: hsvmax[0] = 255 if hsvmax[1] > 255: hsvmax[1] = 255 if hsvmax[2] > 255: hsvmax[2] = 255 cv.InRangeS(hsvimage, cv.Scalar(hsvmin[0], hsvmin[1], hsvmin[2]), cv.Scalar(hsvmax[0], hsvmax[1], hsvmax[2]), maskimage) element = cv.CreateStructuringElementEx(5, 5, 2, 2, cv.CV_SHAPE_RECT) cv.Erode(maskimage, maskimage, element, 1) cv.Dilate(maskimage, maskimage, element, 1) storage = cv.CreateMemStorage(0) cv.Copy(maskimage, blobimage) contour = cv.FindContours(maskimage, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) trackedpoint = None maxtrackedpoint = None maxareasize = 0 #You can tune these value to improve tracking maxarea = 0 minarea = 1 areasize = 0 while contour: bound_rect = cv.BoundingRect(list(contour)) contour = contour.h_next() pt1 = (bound_rect[0], bound_rect[1]) pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3]) areasize = fabs(bound_rect[2] * bound_rect[3]) if (areasize > maxareasize): maxareasize = areasize maxtrackedpoint = (int( (pt1[0] + pt2[0]) / 2), int((pt1[1] + pt2[1]) / 2), 1.0) cv.Rectangle(rgb_image, pt1, pt2, cv.CV_RGB(255, 0, 0), 1) trackedpoint = maxtrackedpoint if (trackedpoint != None): cv.Circle(rgb_image, (trackedpoint[0], trackedpoint[1]), 5, cv.CV_RGB(255, 0, 0), 1) return trackedpoint
import cv2.cv as cv import time capture = cv.CaptureFromCAM(0) cv.SetCaptureProperty(capture, 3, 720) cv.SetCaptureProperty(capture, 4, 480) while True: img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR, 3) hue_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hue_img, cv.CV_BGR2HSV) threshold_img = cv.CreateImage(cv.GetSize(hue_img), 8, 1) cv.InRangeS(hue_img, (110, 50, 50), (120, 255, 255), threshold_img) storage = cv.CreateMemStorage(0) contour = cv.FindContours(threshold_img,storage,cv.CV_RETR_CCOMP,\ cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: rect = cv.BoundingRect(list(contour)) contour = contour.h_next() size = (rect[2] * rect[3]) if size > 100: pt1 = (rect[0], rect[1]) pt2 = (rect[0] + rect[2], rect[1] + rect[3]) cv.Rectangle(img, pt1, pt2, (255, 0, 0)) cv.ShowImage("Colour Tracking", img) if cv.WaitKey(10) == 27: break
if not frame: cv.WaitKey(0) break cv.Smooth(frame, frame, cv.CV_BLUR, 3) hsv = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, hsv, cv.CV_BGR2HSV) thr = cv.CreateImage(cv.GetSize(frame), 8, 1) #Change threshold value cv.InRangeS(hsv, (h1, s1, v1), (h2, s2, v2), thr) moments = cv.Moments(cv.GetMat(thr, 1), 0) area = cv.GetCentralMoment(moments, 0, 0) cv.Line(frame, (160, 0), (160, 240), (0, 0, 255), 3, 8, 0) if (area > 10000): x = cv.GetSpatialMoment(moments, 1, 0) / area y = cv.GetSpatialMoment(moments, 0, 1) / area # overlay = cv.CreateImage(cv.GetSize(frame),8,3) cv.Circle(frame, (int(x), int(y)), 2, (255, 255, 255), 20)
GPIO.output(11,GPIO.LOW) GPIO.output(13,GPIO.LOW) GPIO.output(15,GPIO.LOW) while True: if (GPIO.input(22) == 0): img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR,3) hue_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hue_img, cv.CV_BGR2HSV) #(38,120,60)(75,255,255)#(90,103,130), (145,255,255) #150,100,50, 215,245,255 threshold_img = cv.CreateImage(cv.GetSize(img),8 ,1)#blue cv.InRangeS(hue_img, (80,90,90), (135,185,255), threshold_img) #(38,120,60)(75,255,255)#(65,95,130), (125,190,255) storage = cv.CreateMemStorage(0) contour = cv.FindContours(threshold_img, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: rect = cv.BoundingRect(list(contour)) contour = contour.h_next() size = (rect[2] * rect[3]) mid = (rect[0]+rect[2]/2) diag = (rect[2]**2 + rect[3]**2)**0.5 if (size > 100): pt1 = (rect[0], rect[1]) #left top
def copy_in_range(input_img, output_img, mask_range): '''Copy ,only the pixels with values between mask_range[0] and mask_range[1] from input_img to output_img.''' mask = cv.CreateImage((input_img.width, input_img.height), cv.IPL_DEPTH_8U, 1) cv.InRangeS(input_img, cv.Scalar(mask_range[0]), cv.Scalar(mask_range[1]), mask) cv.Copy(input_img, output_img, mask)
def run(self): logging.debug(' starting run ') global samecolorclient global capture global centroidList #abh global lock #abh global lock2 #abh global lock3 #abh global lock4 #abh mydata = threading.local() #window1=" Color Detection" mydata.window2 = str(self.name) + " Threshold" #cv.NamedWindow(window1,0) lock4.acquire() #abh cv.NamedWindow(mydata.window2, 0) lock4.release() #abh mydata.centroidold = [0, 0] mydata.flag = 0 mydata.roi = [100, 22, 390, 390] #mydata.roi=[95,40,380,350] while True: lock2.acquire() #abh lock4.acquire() #abh mydata.color_image = cv.QueryFrame(capture) lock4.release() #abh lock2.release() #abh if (mydata.flag == 0): lock4.acquire #abh lock4.release #abh mydata.color_image = cv.GetSubRect(mydata.color_image, (100, 22, 390, 390)) lock4.release #abh else: lock4.acquire #abh lock4.release #abh mydata.color_image = cv.GetSubRect( mydata.color_image, (int(mydata.roi[0]), int(mydata.roi[1]), int( mydata.roi[2]), int(mydata.roi[3]))) lock4.release #abh lock4.acquire #abh lock4.release #abh cv.Flip(mydata.color_image, mydata.color_image, 1) cv.Smooth(mydata.color_image, mydata.color_image, cv.CV_MEDIAN, 3, 0) #logging.debug(' Starting getthresholdedimg ') mydata.imghsv = cv.CreateImage(cv.GetSize(mydata.color_image), 8, 3) cv.CvtColor(mydata.color_image, mydata.imghsv, cv.CV_BGR2YCrCb) # Convert image from RGB to HSV mydata.imgnew = cv.CreateImage(cv.GetSize(mydata.color_image), cv.IPL_DEPTH_8U, 1) mydata.imgthreshold = cv.CreateImage( cv.GetSize(mydata.color_image), 8, 1) lock4.release #abh mydata.c = self.color[0] mydata.minc = (float(mydata.c[0]), float(mydata.c[1]), float(mydata.c[2])) mydata.c = self.color[1] mydata.maxc = (float(mydata.c[0]), float(mydata.c[1]), float(mydata.c[2])) lock4.acquire #abh lock4.release #abh cv.InRangeS(mydata.imghsv, cv.Scalar(*(mydata.minc)), cv.Scalar(*(mydata.maxc)), mydata.imgnew) cv.Add(mydata.imgnew, mydata.imgthreshold, mydata.imgthreshold) #logging.debug(' Exiting getthreasholdedimg') #logging.debug('function returned from thresholdedimg') cv.Erode(mydata.imgthreshold, mydata.imgthreshold, None, 1) cv.Dilate(mydata.imgthreshold, mydata.imgthreshold, None, 4) mydata.img2 = cv.CloneImage(mydata.imgthreshold) mydata.storage = cv.CreateMemStorage(0) mydata.contour = cv.FindContours(mydata.imgthreshold, mydata.storage, cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_SIMPLE) lock4.release #abh mydata.points = [] #logging.debug('Starting while contour') while mydata.contour: # Draw bounding rectangles lock4.acquire #abh lock4.release #abh mydata.bound_rect = cv.BoundingRect(list(mydata.contour)) lock4.release #abh mydata.contour = mydata.contour.h_next() mydata.pt1 = (mydata.bound_rect[0], mydata.bound_rect[1]) mydata.pt2 = (mydata.bound_rect[0] + mydata.bound_rect[2], mydata.bound_rect[1] + mydata.bound_rect[3]) mydata.points.append(mydata.pt1) mydata.points.append(mydata.pt2) lock4.acquire #abh lock4.release #abh cv.Rectangle( mydata.color_image, mydata.pt1, mydata.pt2, cv.CV_RGB(mydata.maxc[0], mydata.maxc[1], mydata.maxc[2]), 1) lock4.release #abh # Calculating centroids if (((mydata.bound_rect[2]) * (mydata.bound_rect[3])) < 3500): #logging.debug('Inside iffffffffffffffffffffffff') lock4.acquire #abh lock4.release #abh mydata.centroidx = cv.Round( (mydata.pt1[0] + mydata.pt2[0]) / 2) mydata.centroidy = cv.Round( (mydata.pt1[1] + mydata.pt2[1]) / 2) lock4.release #abh if (mydata.flag == 1): #logging.debug("inside flag1") mydata.centroidx = mydata.roi[0] + mydata.centroidx mydata.centroidy = mydata.roi[1] + mydata.centroidy mydata.centroidnew = [mydata.centroidx, mydata.centroidy] #logging.debug('mydataroi[0] '+str(mydata.roi[0]) + ';centroidx ' + str(mydata.centroidx)) #logging.debug('mydataroi[1] '+str(mydata.roi[1]) + ';centroidy ' + str(mydata.centroidy)) #print mydata.centroidx #abh #print mydata.centroidy #abh mydata.tmpclient = [] lock3.acquire() #abh mydata.tmpclient = samecolorclient[self.i] lock3.release() #abh mydata.distance = math.sqrt( math.pow((mydata.centroidnew[0] - mydata.centroidold[0]), 2) + math.pow((mydata.centroidnew[1] - mydata.centroidold[1]), 2)) #lock.acquire() #abh #abh commented for mydata.j in range(len(mydata.tmpclient)): mydata.client_socket = mydata.tmpclient[mydata.j] #logging.debug('before centroid send...') if (mydata.distance >= 1.50): print 'inside 1.50 ' #self.server_socket.sendto(str(mydata.centroidnew),mydata.client_socket) #abh lock.acquire() #abh centroidList[colorlist.index( self.color)] = mydata.centroidnew #abh del mydata.centroidold[:] #logging.debug(str(centroidList)) self.server_socket.sendto( str(centroidList), mydata.client_socket) #abh lock.release() #abh #logging.debug ('updating done.') #abh #print centroidList #abh mydata.centroidold = mydata.centroidnew[:] else: #self.server_socket.sendto(str(mydata.centroidold),mydata.client_socket) #abh lock.acquire() #abh centroidList[colorlist.index( self.color)] = mydata.centroidold #abh #logging.debug(str(centroidList)) self.server_socket.sendto( str(centroidList), mydata.client_socket) #abh lock.release() #abh #logging.debug ('updating done2.') #abh #print centroidList #abh # logging.debug('byte sent to client') #lock.release() #abh mydata.roi[0] = mydata.centroidx - 50 mydata.roi[1] = mydata.centroidy - 50 if (mydata.roi[0] < 95): mydata.roi[0] = 95 if (mydata.roi[1] < 40): mydata.roi[1] = 40 mydata.roi[2] = 100 mydata.roi[3] = 100 if ((mydata.roi[0] + mydata.roi[2]) > 475): mydata.roi[0] = mydata.roi[0] - ( (mydata.roi[0] + mydata.roi[2]) - 475) if ((mydata.roi[1] + mydata.roi[3]) > 390): mydata.roi[1] = mydata.roi[1] - ( (mydata.roi[1] + mydata.roi[3]) - 390) #del mydata.centroidnew[:] mydata.flag = 1 if mydata.contour is None: mydata.flag = 0 #cv.ShowImage(window1,mydata.color_image) lock4.acquire #abh lock4.release #abh cv.ShowImage(mydata.window2, mydata.img2) lock4.release #abh if cv.WaitKey(33) == 27: #here it was 33 instead of 10 #cv.DestroyWindow(mydata.window1) #cv.DestroyWindow(mydata.window2) break
# do color thresholding src_hsv = cv.CreateImage(cv.GetSize(src2), 8, 3) src_diff = cv.CreateImage(cv.GetSize(src2), 8, 3) src = cv.CreateImage(cv.GetSize(src2), 8, 1) # red = cv.CreateImage(cv.GetSize(src2), 8, 1) # redT = cv.CreateImage(cv.GetSize(src2), 8, 1) # green = cv.CreateImage(cv.GetSize(src2), 8, 1) # blue = cv.CreateImage(cv.GetSize(src2), 8, 1) # cv.Split(src2, red, green, blue, None); # cv.Threshold(red, redT, 20, 255, cv.CV_THRESH_BINARY); cv.Sub(src2, src4, src_diff) cv.CvtColor(src_diff, src_hsv, cv.CV_RGB2HSV) #CV_BGR2HSV_FULL cv.InRangeS(src_hsv, RED_MIN, RED_MAX, src) # cv.NamedWindow("Red", 1) # cv.NamedWindow("Green", 1) # cv.NamedWindow("Blue", 1) # cv.NamedWindow("RedT", 1) # cv.ShowImage("RedT", redT) # cv.ShowImage("Red", red) # cv.ShowImage("Green", green) # cv.ShowImage("Blue", blue) # k = cv.WaitKey(0) % 0x100 # if k == 27: # cv.DestroyAllWindows() # sys.exit(-1)