def redraw(self): edge_img = cv.Mat() # 边缘检测 cv.Canny(self.img_gray, edge_img, self.th1, self.th2) 3### # 计算结果图 if self.show_canny: show_img = cv.Mat() cv.cvtColor(edge_img, show_img, cv.CV_GRAY2BGR) else: show_img = self.img.clone() 4### # 线段检测 theta = self.theta / 180.0 * np.pi lines = cv.HoughLinesP(edge_img, self.rho, theta, self.hough_th, self.minlen, self.maxgap) for line in lines: cv.line(show_img, cv.asPoint(line[:2]), cv.asPoint(line[2:]), cv.CV_RGB(255, 0, 0), 2) 5### # 圆形检测 circles = cv.HoughCircles(self.img_smooth, 3, self.dp, self.mindist, param1=self.param1, param2=self.param2) for circle in circles: cv.circle(show_img, cv.Point(int(circle[0]), int(circle[1])), int(circle[2]), cv.CV_RGB(0, 255, 0), 2) cv.imshow("Hough Demo", show_img)
def __init__(self, **traits): super(HistDemo, self).__init__(**traits) img = cv.imread("lena.jpg") gray_img = cv.Mat() cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY) self.img = gray_img self.img2 = self.img.clone() result = cv.MatND() r = cv.vector_float32([0, 256]) ranges = cv.vector_vector_float32([r, r]) cv.calcHist( cv.vector_Mat([self.img]), channels=cv.vector_int([0, 1]), mask=cv.Mat(), hist=result, histSize=cv.vector_int([256]), ranges=ranges, ) data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:]) self.plot = Plot(data, padding=10) line = self.plot.plot(("x", "y"))[0] self.select_tool = RangeSelection(line, left_button_selects=True) line.tools.append(self.select_tool) self.select_tool.on_trait_change(self._selection_changed, "selection") line.overlays.append(RangeSelectionOverlay(component=line)) cv.imshow("Hist Demo", self.img) self.timer = Timer(50, self.on_timer)
def __init__(self, **traits): super(HistDemo, self).__init__(**traits) img = cv.imread("lena.jpg") gray_img = cv.Mat() cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY) self.img = gray_img self.img2 = self.img.clone() result = cv.MatND() r = cv.vector_float32([0, 256]) ranges = cv.vector_vector_float32([r, r]) cv.calcHist(cv.vector_Mat([self.img]), channels=cv.vector_int([0, 1]), mask=cv.Mat(), hist=result, histSize=cv.vector_int([256]), ranges=ranges) data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:]) self.plot = Plot(data, padding=10) line = self.plot.plot(("x", "y"))[0] self.select_tool = RangeSelection(line, left_button_selects=True) line.tools.append(self.select_tool) self.select_tool.on_trait_change(self._selection_changed, "selection") line.overlays.append(RangeSelectionOverlay(component=line)) cv.imshow("Hist Demo", self.img) self.timer = Timer(50, self.on_timer)
def redraw(self): edge_img = cv.Mat() # 边缘检测 cv.Canny(self.img_gray, edge_img, self.th1, self.th2) 3 ### # 计算结果图 if self.show_canny: show_img = cv.Mat() cv.cvtColor(edge_img, show_img, cv.CV_GRAY2BGR) else: show_img = self.img.clone() 4 ### # 线段检测 theta = self.theta / 180.0 * np.pi lines = cv.HoughLinesP(edge_img, self.rho, theta, self.hough_th, self.minlen, self.maxgap) for line in lines: cv.line(show_img, cv.asPoint(line[:2]), cv.asPoint(line[2:]), cv.CV_RGB(255, 0, 0), 2) 5 ### # 圆形检测 circles = cv.HoughCircles(self.img_smooth, 3, self.dp, self.mindist, param1=self.param1, param2=self.param2) for circle in circles: cv.circle(show_img, cv.Point(int(circle[0]), int(circle[1])), int(circle[2]), cv.CV_RGB(0, 255, 0), 2) cv.imshow("Hough Demo", show_img)
def __init__(self, *args, **kwargs): super(SURFDemo, self).__init__(*args, **kwargs) img = cv.imread("lena_small.jpg") self.m = np.array([[0.8, -0.6, 60], [0.6, 0.7, -20]]) self.img1 = cv.Mat() cv.cvtColor(img, self.img1, cv.CV_BGR2GRAY) self.affine() self.on_trait_change(self.redraw, "max_distance,draw_circle") self.on_trait_change(self.recalculate, "m,hessian_th,octaves,layers") self.recalculate() self.redraw()
def __init__(self, *args, **kwargs): super(SURFDemo, self).__init__(*args, **kwargs) img = cv.imread("lena_small.jpg") self.m = np.array([[0.8,-0.6,60],[0.6,0.7,-20]]) self.img1 = cv.Mat() cv.cvtColor(img, self.img1, cv.CV_BGR2GRAY) self.affine() self.on_trait_change(self.redraw, "max_distance,draw_circle") self.on_trait_change(self.recalculate, "m,hessian_th,octaves,layers") self.recalculate() self.redraw()
def grayspace(src): ''' ''' # dst = cv.Mat(src.size(), cv.CV_8UC1)#cv.Size(src.cols, src.rows), cv.CV_8UC1) # cv.cvtColor(src, dst, cv.CV_BGR2GRAY) if src.channels() > 1: dst = cv.Mat(src.size(), cv.CV_8UC1) # cv.Size(src.cols, src.rows), cv.CV_8UC1) cv.cvtColor(src, dst, cv.CV_BGR2GRAY) else: dst = src return dst
def process(self, input_images, connected_outs): if len(input_images) == 0: return FAIL src = input_images['Input'] dist_res = int( self.getParamContent('Distance resolution') ) angle_res = int( self.getParamContent('Angle resolution (degrees)') ) acc_thresh = int( self.getParamContent('Accumulator threshold') ) min_length = int( self.getParamContent('Minimum length') ) max_gap = int( self.getParamContent('Maximum gap') ) choice = self.getParamContent("Type of Hough transform") if src.ndim > 2: print "In '%s': The hough transform takes a binary image (or 8-bit) as input." %self.name return FAIL color_dst = numpy.empty( (src.shape[0], src.shape[1], 3),dtype='uint8' ) pycv.cvtColor( pycv.asMat(src), pycv.asMat(color_dst), pycv.CV_GRAY2BGR ) if choice == "Standard": lines = pycv.HoughLines( pycv.asMat(src), dist_res, pycv.CV_PI/angle_res, acc_thresh ) margin = 0.04 n=8 pi = math.pi h,w = src.shape[0:2] for i in range(min(len(lines), int(self.getParamContent("draw # lines")))): l = lines[i] rho = l[0] theta = l[1] if theta > 3*pi/4: theta-=pi if abs(rho)<w/n and abs(theta)<margin: pass elif abs(rho)>w-w/n and abs(theta)<margin: pass elif abs(rho)<h/n and abs(theta-pi/2)<margin: pass elif abs(rho)>h-h/n and abs(theta-pi/2)<margin: pass else: continue a = math.cos(theta) b = math.sin(theta) x0 = a*rho y0 = b*rho pt1 = pycv.Point( int(round(x0 + 2000*(-b))), int(round(y0 + 2000*(a))) ) pt2 = pycv.Point( int(round(x0 - 2000*(-b))), int(round(y0 - 2000*(a))) ) pycv.line( pycv.asMat(color_dst), pt1, pt2, pycv.CV_RGB(random.randint(0,255), random.randint(0,255), random.randint(0,255)), 2, 8 ) else: lines = pycv.HoughLinesP( pycv.asMat(src), dist_res, pycv.CV_PI/angle_res, acc_thresh, min_length, max_gap ) for l in lines: pycv.line( pycv.asMat(color_dst), pycv.Point(int(l[0]), int(l[1])), pycv.Point(int(l[2]), int(l[3])), pycv.CV_RGB(*getRandColor()), 2, 8 ) self.lines = [(item[0],item[1]) for item in lines] return {self.output_names[0] : color_dst, self.output_names[1]:self.lines}
def colorspace(src, cs=None): ''' ''' if cs is None: cs = cv.CV_GRAY2BGR if src.channels() == 1: dst = cv.Mat(cv.Size(src.cols, src.rows), cv.CV_8UC3) # dst = new_dst(src, nchannels=3) cv.cvtColor(src, dst, cs) else: dst = src return dst
def __init__(self, *args, **kwargs): super(HoughDemo, self).__init__(*args, **kwargs) self.img = cv.imread("stuff.jpg") self.img_gray = cv.Mat() cv.cvtColor(self.img, self.img_gray, cv.CV_BGR2GRAY) self.img_smooth = self.img_gray.clone() cv.smooth(self.img_gray, self.img_smooth, cv.CV_GAUSSIAN, 7, 7, 0, 0) self.redraw() self.on_trait_change(self.redraw, "th1,th2,show_canny,rho,theta,hough_th,minlen,maxgap,dp,mindist,param1,param2")
def detect(frame, cascade, fallbackCascade): minPairSize = pyopencv.Size(20, 20) haarScale = 1.1 minNeighbors = 0 haarFlags = pyopencv.CascadeClassifier.FIND_BIGGEST_OBJECT grayImg = pyopencv.Mat() pyopencv.cvtColor(frame, grayImg, pyopencv.CV_BGR2GRAY) pyopencv.equalizeHist(grayImg, grayImg) eyes = cascade.detectMultiScale(grayImg, haarScale, minNeighbors, haarFlags, minPairSize) if len(eyes) == 0: eyes = fallbackCascade.detectMultiScale(grayImg, haarScale, minNeighbors, haarFlags |pyopencv.CascadeClassifier.SCALE_IMAGE, minPairSize) return eyes
def __init__(self): #读入图像 img = cv.imread("lena_full.jpg") img2 = cv.Mat() cv.cvtColor(img, img2, cv.CV_BGR2GRAY) img = cv.Mat() cv.resize(img2, img, cv.Size(N, N)) self.fimg = fft.fft2(img[:]) # 图像的频域信号 mag_img = np.log10(np.abs(self.fimg)) # 创建计算用图像 filtered_img = np.zeros((N, N), dtype=np.float) self.mask = np.zeros((N, N), dtype=np.float) self.mask_img = cv.asMat(self.mask) # 在self.mask上绘制多边形用的图像 # 创建数据源 self.data = ArrayPlotData(mag_img=fft.fftshift(mag_img), filtered_img=filtered_img, mask_img=self.mask) # 创建三个图像绘制框以及容器 meg_plot, img = self.make_image_plot("mag_img") mask_plot, _ = self.make_image_plot("mask_img") filtered_plot, _ = self.make_image_plot("filtered_img") self.plot = HPlotContainer(meg_plot, mask_plot, filtered_plot) # 创建套索工具 lasso_selection = LassoSelection(component=img) lasso_overlay = LassoOverlay(lasso_selection=lasso_selection, component=img, selection_alpha=0.3) img.tools.append(lasso_selection) img.overlays.append(lasso_overlay) self.lasso_selection = lasso_selection # 监听套索工具的事件、开启时钟事件 lasso_selection.on_trait_change(self.lasso_updated, "disjoint_selections") self.timer = Timer(50, self.on_timer)
def __init__(self): #读入图像 img = cv.imread("lena_full.jpg") img2 = cv.Mat() cv.cvtColor(img, img2, cv.CV_BGR2GRAY) img = cv.Mat() cv.resize(img2, img, cv.Size(N, N)) self.fimg = fft.fft2(img[:]) # 图像的频域信号 mag_img = np.log10(np.abs(self.fimg)) # 创建计算用图像 filtered_img = np.zeros((N, N), dtype=np.float) self.mask = np.zeros((N, N), dtype=np.float) self.mask_img = cv.asMat(self.mask) # 在self.mask上绘制多边形用的图像 # 创建数据源 self.data = ArrayPlotData( mag_img = fft.fftshift(mag_img), filtered_img = filtered_img, mask_img = self.mask ) # 创建三个图像绘制框以及容器 meg_plot, img = self.make_image_plot("mag_img") mask_plot, _ = self.make_image_plot("mask_img") filtered_plot, _ = self.make_image_plot("filtered_img") self.plot = HPlotContainer(meg_plot, mask_plot, filtered_plot) # 创建套索工具 lasso_selection = LassoSelection(component=img) lasso_overlay = LassoOverlay(lasso_selection = lasso_selection, component=img, selection_alpha=0.3) img.tools.append(lasso_selection) img.overlays.append(lasso_overlay) self.lasso_selection = lasso_selection # 监听套索工具的事件、开启时钟事件 lasso_selection.on_trait_change(self.lasso_updated, "disjoint_selections") self.timer = Timer(50, self.on_timer)
# -*- coding: utf-8 -*- import numpy as np from numpy import fft import pyopencv as cv import matplotlib.pyplot as plt N = 256 img = cv.imread("lena_full.jpg") img2 = cv.Mat() cv.cvtColor(img, img2, cv.CV_BGR2GRAY) img = cv.Mat() cv.resize(img2, img, cv.Size(N, N)) fimg = fft.fft2(img[:]) mag_img = np.log10(np.abs(fimg)) shift_mag_img = fft.fftshift(mag_img) rects = [(80, 125, 85, 130), (90, 90, 95, 95), (150, 10, 250, 250), (110, 110, 146, 146)] filtered_results = [] for i, (x0, y0, x1, y1) in enumerate(rects): mask = np.zeros((N, N), dtype=np.bool) mask[x0:x1 + 1, y0:y1 + 1] = True mask[N - x1:N - x0 + 1, N - y1:N - y0 + 1] = True mask = fft.fftshift(mask) fimg2 = fimg * mask filtered_img = fft.ifft2(fimg2).real filtered_results.append(filtered_img) ### 绘图部分 ###
def draw(frame, eyes, glasses): global prevROI imgSize = frame.size() if len(eyes) == 0: region = None if prevROI: region = pyopencv.Rect() roiCX = prevROI[0] + prevROI[2]/2.0 roiCY = prevROI[1] + prevROI[3]/2.0 newWidth = fadeoutLambda * prevROI[2] newHeight = fadeoutLambda * prevROI[3]/2.0 newX = roiCX - newWidth/2.0 newY = roiCY - newHeight/2.0 region.x = int(round(newX)) region.y = int(round(newY)) region.width = int(round(newWidth)) region.height = int(round(newHeight)) prevROI = (newX, newY, newWidth, newHeight) if region.width < fadeoutLim or region.height < fadeoutLim: region = None previousROI = None else: region = eyes[0] if not prevROI: prevROI = (region.x*1.0, region.y*1.0, region.width*1.0, region.height*1.0) else: newWidth = (roiLambda*prevROI[2] + (1.0-roiLambda)*region.width*roiScaler) newHeight = (roiLambda*prevROI[3] + (1.0-roiLambda)*region.height*roiScaler) roiCX = (roiLambda*(prevROI[0] + prevROI[2]/2.0) + (1.0-roiLambda)*(region.x + region.width/2.0)) roiCY = (roiLambda*(prevROI[1] + prevROI[3]/2.0) + (1.0-roiLambda)*(region.y + region.height/2.0)) newX = roiCX - newWidth/2.0 newY = roiCY - newHeight/2.0 if newX < 0: newX = 0 if newY < 0: newY = 0 if newX + newWidth > imgSize[0]: newWidth = imgSize[0] - newX if newY + newHeight > imgSize[1]: newHeight = imgSize[1] - newY prevROI = (newX, newY, newWidth, newHeight) region.x = int(round(newX)) region.y = int(round(newY)) region.width = int(round(newWidth)) region.height = int(round(newHeight)) if region.width < fadeoutLim or region.height < fadeoutLim: region = None previousROI = None if region: roiSize = region.size() faceROI = frame(region) glasses = glasses.resize((roiSize[0], roiSize[1]), Image.BICUBIC) glasses = pyopencv.Mat.from_pil_image(glasses) mask = pyopencv.Mat() pyopencv.cvtColor(glasses, mask, pyopencv.CV_RGB2GRAY) pyopencv.subtract(faceROI, faceROI, faceROI, mask) pyopencv.add(faceROI, glasses, faceROI, mask) return frame
def process(self, input_images, connected_outs): if len(input_images) == 0: return FAIL src = input_images['Input'] dist_res = int(self.getParamContent('Distance resolution')) angle_res = int(self.getParamContent('Angle resolution (degrees)')) acc_thresh = int(self.getParamContent('Accumulator threshold')) min_length = int(self.getParamContent('Minimum length')) max_gap = int(self.getParamContent('Maximum gap')) choice = self.getParamContent("Type of Hough transform") if src.ndim > 2: print "In '%s': The hough transform takes a binary image (or 8-bit) as input." % self.name return FAIL color_dst = numpy.empty((src.shape[0], src.shape[1], 3), dtype='uint8') pycv.cvtColor(pycv.asMat(src), pycv.asMat(color_dst), pycv.CV_GRAY2BGR) if choice == "Standard": lines = pycv.HoughLines(pycv.asMat(src), dist_res, pycv.CV_PI / angle_res, acc_thresh) margin = 0.04 n = 8 pi = math.pi h, w = src.shape[0:2] for i in range( min(len(lines), int(self.getParamContent("draw # lines")))): l = lines[i] rho = l[0] theta = l[1] if theta > 3 * pi / 4: theta -= pi if abs(rho) < w / n and abs(theta) < margin: pass elif abs(rho) > w - w / n and abs(theta) < margin: pass elif abs(rho) < h / n and abs(theta - pi / 2) < margin: pass elif abs(rho) > h - h / n and abs(theta - pi / 2) < margin: pass else: continue a = math.cos(theta) b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = pycv.Point(int(round(x0 + 2000 * (-b))), int(round(y0 + 2000 * (a)))) pt2 = pycv.Point(int(round(x0 - 2000 * (-b))), int(round(y0 - 2000 * (a)))) pycv.line( pycv.asMat(color_dst), pt1, pt2, pycv.CV_RGB(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 2, 8) else: lines = pycv.HoughLinesP(pycv.asMat(src), dist_res, pycv.CV_PI / angle_res, acc_thresh, min_length, max_gap) for l in lines: pycv.line(pycv.asMat(color_dst), pycv.Point(int(l[0]), int(l[1])), pycv.Point(int(l[2]), int(l[3])), pycv.CV_RGB(*getRandColor()), 2, 8) self.lines = [(item[0], item[1]) for item in lines] return { self.output_names[0]: color_dst, self.output_names[1]: self.lines }
# -*- coding: utf-8 -*- import numpy as np from numpy import fft import pyopencv as cv import matplotlib.pyplot as plt N = 256 img = cv.imread("lena_full.jpg") img2 = cv.Mat() cv.cvtColor(img, img2, cv.CV_BGR2GRAY) img = cv.Mat() cv.resize(img2, img, cv.Size(N, N)) fimg = fft.fft2(img[:]) mag_img = np.log10(np.abs(fimg)) shift_mag_img = fft.fftshift(mag_img) rects = [(80,125,85,130),(90,90,95,95), (150, 10, 250, 250), (110, 110, 146, 146)] filtered_results = [] for i, (x0, y0, x1, y1) in enumerate(rects): mask = np.zeros((N, N), dtype=np.bool) mask[x0:x1+1, y0:y1+1] = True mask[N-x1:N-x0+1, N-y1:N-y0+1] = True mask = fft.fftshift(mask) fimg2 = fimg * mask filtered_img = fft.ifft2(fimg2).real
cv.Scalar(255,255,0), cv.Scalar(255,0,0), cv.Scalar(255,0,255), cv.Scalar(255,255,255), ] # read the two images object_color = cv.imread( object_filename, cv.CV_LOAD_IMAGE_COLOR ) image = cv.imread( scene_filename, cv.CV_LOAD_IMAGE_GRAYSCALE ) if not object_color or not image: print("Can not load %s and/or %s\n" \ "Usage: find_obj [<object_filename> <scene_filename>]\n" \ % (object_filename, scene_filename)) exit(-1) object = cv.Mat(object_color.size(), cv.CV_8UC1) cv.cvtColor( object_color, object, cv.CV_BGR2GRAY ) # corners src_corners = [cv.Point(0,0), cv.Point(object.cols, 0), cv.Point(object.cols, object.rows), cv.Point(0, object.rows)] dst_corners = [cv.Point()]*4 # find keypoints on both images surf = cv.SURF(500, 4, 2, True) mask = cv.Mat() tt = float(cv.getTickCount()) objectKeypoints = cv.vector_KeyPoint() objectDescriptors = surf(object, mask, objectKeypoints) print("Object Descriptors: %d\n" % len(objectKeypoints)) imageKeypoints = cv.vector_KeyPoint() imageDescriptors = surf(image, mask, imageKeypoints) print("Image Descriptors: %d\n" % len(imageKeypoints))
# -*- coding: utf-8 -*- import pyopencv as cv import numpy as np img = cv.imread("fruits_section.jpg") img_hsv = cv.Mat() cv.cvtColor(img, img_hsv, cv.CV_BGR2HSV) channels = cv.vector_int([0, 1]) result = cv.MatND() r = cv.vector_float32([0, 256]) ranges = cv.vector_vector_float32([r, r]) cv.calcHist(cv.vector_Mat([img_hsv]), channels, cv.Mat(), result, cv.vector_int([40, 40]), ranges) result[:] /= np.max(result[:]) / 255 2 ### img2 = cv.imread("fruits.jpg") img_hsv2 = cv.Mat() cv.cvtColor(img2, img_hsv2, cv.CV_BGR2HSV) img_bp = cv.Mat() cv.calcBackProject(cv.vector_Mat([img_hsv2]), channels=channels, hist=result, backProject=img_bp, ranges=ranges) 3 ###
# -*- coding: utf-8 -*- import pyopencv as cv import numpy as np img = cv.imread("fruits_section.jpg") img_hsv = cv.Mat() cv.cvtColor(img, img_hsv, cv.CV_BGR2HSV) channels = cv.vector_int([0, 1]) result = cv.MatND() r = cv.vector_float32([0, 256]) ranges = cv.vector_vector_float32([r, r]) cv.calcHist(cv.vector_Mat([img_hsv]), channels, cv.Mat(), result, cv.vector_int([40, 40]), ranges) result[:] /= np.max(result[:]) / 255 2### img2 = cv.imread("fruits.jpg") img_hsv2 = cv.Mat() cv.cvtColor(img2, img_hsv2, cv.CV_BGR2HSV) img_bp = cv.Mat() cv.calcBackProject(cv.vector_Mat([img_hsv2]), channels=channels, hist=result, backProject=img_bp, ranges = ranges) 3###
cv.Scalar(255, 255, 0), cv.Scalar(255, 0, 0), cv.Scalar(255, 0, 255), cv.Scalar(255, 255, 255), ] # read the two images object_color = cv.imread(object_filename, cv.CV_LOAD_IMAGE_COLOR) image = cv.imread(scene_filename, cv.CV_LOAD_IMAGE_GRAYSCALE) if not object_color or not image: print("Can not load %s and/or %s\n" \ "Usage: find_obj [<object_filename> <scene_filename>]\n" \ % (object_filename, scene_filename)) exit(-1) object = cv.Mat(object_color.size(), cv.CV_8UC1) cv.cvtColor(object_color, object, cv.CV_BGR2GRAY) # corners src_corners = [ cv.Point(0, 0), cv.Point(object.cols, 0), cv.Point(object.cols, object.rows), cv.Point(0, object.rows) ] dst_corners = [cv.Point()] * 4 # find keypoints on both images surf = cv.SURF(500, 4, 2, True) mask = cv.Mat() tt = float(cv.getTickCount()) objectKeypoints = cv.vector_KeyPoint()