def processImage(self, curframe): cv.Smooth(curframe, curframe) #Remove false positives if not self.absdiff_frame: #For the first time put values in difference, temp and moving_average self.absdiff_frame = cv.CloneImage(curframe) self.previous_frame = cv.CloneImage(curframe) cv.Convert( curframe, self.average_frame ) #Should convert because after runningavg take 32F pictures else: cv.RunningAvg(curframe, self.average_frame, 0.05) #Compute the average cv.Convert(self.average_frame, self.previous_frame) #Convert back to 8U frame cv.AbsDiff(curframe, self.previous_frame, self.absdiff_frame) # moving_average - curframe cv.CvtColor( self.absdiff_frame, self.gray_frame, cv.CV_RGB2GRAY) #Convert to gray otherwise can't do threshold cv.Threshold(self.gray_frame, self.gray_frame, 50, 255, cv.CV_THRESH_BINARY) cv.Dilate(self.gray_frame, self.gray_frame, None, 15) #to get object blobs cv.Erode(self.gray_frame, self.gray_frame, None, 10)
def extract_bright(grey_img, histogram=False): """ Extracts brightest part of the image. Expected to be the LEDs (provided that there is a dark background) Returns a Thresholded image histgram defines if we use the hist calculation to find the best margin """ ## Searches for image maximum (brightest pixel) # We expect the LEDs to be brighter than the rest of the image [minVal, maxVal, minLoc, maxLoc] = cv2.MinMaxLoc(grey_img) print "Brightest pixel val is %d" % (maxVal) #We retrieve only the brightest part of the image # Here is use a fixed margin (80%), but you can use hist to enhance this one if 0: ## Histogram may be used to wisely define the margin # We expect a huge spike corresponding to the mean of the background # and another smaller spike of bright values (the LEDs) hist = grey_histogram(img, nBins=64) [hminValue, hmaxValue, hminIdx, hmaxIdx] = cv2.GetMinMaxHistValue(hist) margin = 0 # statistics to be calculated using hist data else: margin = 0.8 thresh = int(maxVal * margin) # in pix value to be extracted print "Threshold is defined as %d" % (thresh) thresh_img = cv2.CreateImage(cv2.GetSize(img), img.depth, 1) cv2.Threshold(grey_img, thresh_img, thresh, 255, cv2.CV_THRESH_BINARY) return thresh_img
def get_hands(image): """ Returns the hand as white on black. Uses value in HSV to determine hands.""" size = cv2.GetSize(image) hsv = cv2.CreateImage(size, 8, 3) hue = cv2.CreateImage(size, 8, 1) sat = cv2.CreateImage(size, 8, 1) val = cv2.CreateImage(size, 8, 1) hands = cv2.CreateImage(size, 8, 1) cv2.Cv2tColor(image, hsv, cv2.CV2_BGR2HSV) cv2.Split(hsv, hue, sat, val, None) cv2.ShowImage('Live', image) cv2.ShowImage('Hue', hue) cv2.ShowImage('Saturation', sat) cv2.Threshold( hue, hue, 10, 255, cv2.CV2_THRESH_TOZERO) #set to 0 if <= 10, otherwise leave as is cv2.Threshold( hue, hue, 244, 255, cv2.CV2_THRESH_TOZERO_INV) #set to 0 if > 244, otherwise leave as is cv2.Threshold(hue, hue, 0, 255, cv2.CV2_THRESH_BINARY_INV) #set to 255 if = 0, otherwise 0 cv2.Threshold( sat, sat, 64, 255, cv2.CV2_THRESH_TOZERO) #set to 0 if <= 64, otherwise leave as is cv2.EqualizeHist(sat, sat) cv2.Threshold(sat, sat, 64, 255, cv2.CV2_THRESH_BINARY) #set to 0 if <= 64, otherwise 255 cv2.ShowImage('Saturation threshold', sat) cv2.ShowImage('Hue threshold', hue) cv2.Mul(hue, sat, hands) #smooth + threshold to filter noise # cv2.Smooth(hands, hands, smoothtype=cv2.CV2_GAUSSIAN, param1=13, param2=13) # cv2.Threshold(hands, hands, 200, 255, cv2.CV2_THRESH_BINARY) cv2.ShowImage('Hands', hands) return hands
def processImage(self, frame): cv.CvtColor(frame, self.frame2gray, cv.CV_RGB2GRAY) #Absdiff to get the difference between to the frames cv.AbsDiff(self.frame1gray, self.frame2gray, self.res) #Remove the noise and do the threshold cv.Smooth(self.res, self.res, cv.CV_BLUR, 5, 5) cv.MorphologyEx(self.res, self.res, None, None, cv.CV_MOP_OPEN) cv.MorphologyEx(self.res, self.res, None, None, cv.CV_MOP_CLOSE) cv.Threshold(self.res, self.res, 10, 255, cv.CV_THRESH_BINARY_INV)
import cv2 as cv import math im = cv.imread('D:/1.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE) pi = math.pi #Pi value dst = cv.CreateImage(cv.GetSize(im), 8, 1) cv.Canny(im, dst, 200, 200) cv.Threshold(dst, dst, 100, 255, cv.CV_THRESH_BINARY) #---- Standard ---- color_dst_standard = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(im, color_dst_standard, cv.CV_GRAY2BGR) #Create output image in RGB to put red lines lines = cv.HoughLines2(dst, cv.CreateMemStorage(0), cv.CV_HOUGH_STANDARD, 1, pi / 180, 100, 0, 0) for (rho, theta) in lines[:100]: a = math.cos(theta) #Calculate orientation in order to print them b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a))) pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a))) cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) #Draw the line #---- Probabilistic ---- color_dst_proba = cv.CreateImage(cv.GetSize(im), 8, 3)
import cv2 as cv orig = cv.imread('lena.png') #im = cv.CreateImage(cv.GetSize(orig), 8, 1) im = cv.cvtColor(orig,cv.COLOR_BGR2GRAY) #cv.CvtColor(orig, im, cv.CV_BGR2GRAY) #Keep the original in colour to draw contours in the end cv.Threshold(im, im, 128, 255, cv.CV_THRESH_BINARY) cv.ShowImage("Threshold 1", im) element = cv.CreateStructuringElementEx(5*2+1, 5*2+1, 5, 5, cv.CV_SHAPE_RECT) cv.MorphologyEx(im, im, None, element, cv.CV_MOP_OPEN) #Open and close to make appear contours cv.MorphologyEx(im, im, None, element, cv.CV_MOP_CLOSE) cv.Threshold(im, im, 128, 255, cv.CV_THRESH_BINARY_INV) cv.ShowImage("After MorphologyEx", im) # -------------------------------- vals = cv.CloneImage(im) #Make a clone because FindContours can modify the image contours=cv.FindContours(vals, cv.CreateMemStorage(0), cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE, (0,0)) _red = (0, 0, 255); #Red for external contours _green = (0, 255, 0);# Gren internal contours levels=2 #1 contours drawn, 2 internal contours as well, 3 ... cv.DrawContours (orig, contours, _red, _green, levels, 2, cv.CV_FILLED) #Draw contours on the colour image cv.ShowImage("Image", orig) cv.WaitKey(0)
def run(self): # Capture first frame to get size frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) width = frame.width height = frame.height surface = width * height #Surface area of the image cursurface = 0 #Hold the current surface that have changed grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) difference = None while True: color_image = cv.QueryFrame(self.capture) cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0) #Remove false positives if not difference: #For the first time put values in difference, temp and moving_average difference = cv.CloneImage(color_image) temp = cv.CloneImage(color_image) cv.ConvertScale(color_image, moving_average, 1.0, 0.0) else: cv.RunningAvg(color_image, moving_average, 0.020, None) #Compute the average # Convert the scale of the moving average. cv.ConvertScale(moving_average, temp, 1.0, 0.0) # Minus the current frame from the moving average. cv.AbsDiff(color_image, temp, difference) #Convert the image so that it can be thresholded cv.CvtColor(difference, grey_image, cv.CV_RGB2GRAY) cv.Threshold(grey_image, grey_image, 70, 255, cv.CV_THRESH_BINARY) cv.Dilate(grey_image, grey_image, None, 18) #to get object blobs cv.Erode(grey_image, grey_image, None, 10) # Find contours storage = cv.CreateMemStorage(0) contours = cv.FindContours(grey_image, storage, cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_SIMPLE) backcontours = contours #Save contours while contours: #For all contours compute the area cursurface += cv.ContourArea(contours) contours = contours.h_next() avg = ( cursurface * 100 ) / surface #Calculate the average of contour area on the total size if avg > self.ceil: print("Something is moving !") #print avg,"%" cursurface = 0 #Put back the current surface to 0 #Draw the contours on the image _red = (0, 0, 255) #Red for external contours _green = (0, 255, 0) # Gren internal contours levels = 1 #1 contours drawn, 2 internal contours as well, 3 ... cv.DrawContours(color_image, backcontours, _red, _green, levels, 2, cv.CV_FILLED) cv.ShowImage("Target", color_image) # Listen for ESC or ENTER key c = cv.WaitKey(7) % 0x100 if c == 27 or c == 10: break
# coding:UTF-8 import cv2 from src import App img_file = App.resource_file("/opencv/timg.jpg") im = cv2.imread(img_file, 0) sobx = cv2.CreateImage(cv2.GetSize(im), cv2.IPL_DEPTH_16S, 1) #Sobel with x-order=1 cv2.Sobel(im, sobx, 1, 0, 3) soby = cv2.CreateImage(cv2.GetSize(im), cv2.IPL_DEPTH_16S, 1) #Sobel withy-oder=1 cv2.Sobel(im, soby, 0, 1, 3) cv2.Abs(sobx, sobx) cv2.Abs(soby, soby) result = cv2.CloneImage(im) #Add the two results together. cv2.Add(sobx, soby, result) cv2.Threshold(result, result, 100, 255, cv2.CV_THRESH_BINARY_INV) cv2.ShowImage('Image', im) cv2.ShowImage('Result', result) cv2.WaitKey(0)
import csv import glob #Importing the dataset label = "Uninfected" dirList = glob.glob("cell_images/" + label + "*/.png") file = open("D:/dataset.csv", "a") #Accessing files for img_path in dirList: Image = cv2.imread("img_path") Image = cv2.GaussainBlur(Image, (5 * 5), 2) #image smooth Image_Grey = cv2.cvtColor( Image, cv2.COLOR_BGR2GREY) #Converting image into greyscale ret, thre = cv2.Threshold(Image_Grey, 127, 254, 0) # Applying threhold value to every pixel contours = cv2.findContours(thre, 1, 2) file.write(label) file.write(",") for i in range(5): try: area = cv2.contourArea(contours[i]) file.write(str(area)) except: file.write("0") file.write(",")
import cv2 import tesseract gray = cv2.LoadImage('sample.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) cv2.Threshold(gray, gray, 231, 255, cv2.CV_THRESH_BINARY) api = tesseract.TessBaseAPI() api.Init(".", "eng", tesseract.OEM_DEFAULT) api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyz") api.SetPageSegMode(tesseract.PSM_SINGLE_WORD) tesseract.SetCvImage(gray, api) print api.GetUTF8Text()
def process_image(self, slider_pos): global cimg, source_image1, ellipse_size, maxf, maxs, eoc, lastcx,lastcy,lastr """ This function finds contours, draws them and their approximation by ellipses. """ stor = cv.CreateMemStorage() # Create the destination images cimg = cv.CloneImage(self.source_image) cv.Zero(cimg) image02 = cv.CloneImage(self.source_image) cv.Zero(image02) image04 = cv.CreateImage(cv.GetSize(self.source_image), cv.IPL_DEPTH_8U, 3) cv.Zero(image04) # Threshold the source image. This needful for cv.FindContours(). cv.Threshold(self.source_image, image02, slider_pos, 255, cv.CV_THRESH_BINARY) # Find all contours. cont = cv.FindContours(image02, stor, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, (0, 0)) maxf = 0 maxs = 0 size1 = 0 for c in contour_iterator(cont): if len(c) > ellipse_size: PointArray2D32f = cv.CreateMat(1, len(c), cv.CV_32FC2) for (i, (x, y)) in enumerate(c): PointArray2D32f[0, i] = (x, y) # Draw the current contour in gray gray = cv.CV_RGB(100, 100, 100) cv.DrawContours(image04, c, gray, gray,0,1,8,(0,0)) if iter == 0: strng = segF + '/' + 'contour1.png' cv.SaveImage(strng,image04) color = (255,255,255) (center, size, angle) = cv.FitEllipse2(PointArray2D32f) # Convert ellipse data from float to integer representation. center = (cv.Round(center[0]), cv.Round(center[1])) size = (cv.Round(size[0] * 0.5), cv.Round(size[1] * 0.5)) if iter == 1: if size[0] > size[1]: size2 = size[0] else: size2 = size[1] if size2 > size1: size1 = size2 size3 = size # Fits ellipse to current contour. if eoc == 0 and iter == 2: rand_val = abs((lastr - ((size[0]+size[1])/2))) if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.5: lastcx = center[0] lastcy = center[1] lastr = (size[0]+size[1])/2 if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.4: cv.Ellipse(cimg, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) cv.Ellipse(source_image1, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) elif eoc == 1 and iter == 2: (int,cntr,rad) = cv.MinEnclosingCircle(PointArray2D32f) cntr = (cv.Round(cntr[0]), cv.Round(cntr[1])) rad = (cv.Round(rad)) if maxf == 0 and maxs == 0: cv.Circle(cimg, cntr, rad, color, 1, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxf = rad elif (maxf > 0 and maxs == 0) and abs(rad - maxf) > 30: cv.Circle(cimg, cntr, rad, color, 2, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxs = len(c) if iter == 1: temp3 = 2*abs(size3[1] - size3[0]) if (temp3 > 40): eoc = 1
def thresholdImage(im, value, filter=cv.CV_THRESH_BINARY_INV): cv.Threshold(im, im, value, 255, filter)