def covR(data): #Calculation of image covariance matrix as a function of mask radius R #Find the image center-of-mass xbar, ybar, cov = image_raw_moments(data) center = [xbar, ybar] p2x, p2y = imtl.ImageFit(data, 1.0) print "Image center is at: ", p2x[0], p2y[0] center = [p2x[0], p2y[0]] #Define image size h, w = data.shape[:2] cov_array = np.zeros((m, 4)) #Loop over radius size (program core loop) for i in range(0, m): factor = int(max(semi_a0, semi_b0) / min(semi_a0, semi_b0)) semi_a = semi_a0 + i * step semi_b = semi_b0 + i * step mask = create_elliptical_mask(h, w, center, semi_a, semi_b, skew) temp = data.copy() #zero all the points outside of region of interest temp[~mask] = 0.0 xbart, ybart, covt = image_raw_moments(temp) cov_array[i, :] = np.ndarray.flatten(covt) print semi_a, semi_b, i #store calculated moments as a function of radius size for analysis return cov_array
def __init__(self, word_list): frame_xrc.xrcWordList.__init__(self, None) # load some images into an image list #创建图像列表 self.word_list = word_list self.il = wx.ImageList(200, 200, True) for im, info in word_list: try: img = ImageTool.pilImage_to_wxImage(im) except: print im, im.size, info continue bmp = wx.BitmapFromImage(img) self.il.Add(bmp) # create the list control #创建列表窗口部件 self.list = xrc.XRCCTRL(self, "img_list_ctrl") # assign the image list to it self.list.AssignImageList(self.il, wx.IMAGE_LIST_NORMAL) # create some items for the list #为列表创建一些项目 for x in range(len(word_list)): img_index = x name = str(word_list[x][1]) self.list.InsertImageStringItem(x, name, img_index) self.BindEvent()
def __init__(self, word_list): wx.Frame.__init__(self, None, -1, "PyOCR", size=(600, 400)) # load some images into an image list # 创建图像列表 w, h = word_list[0][0].size il = wx.ImageList(w, h, True) for im, _x, _y in word_list: # im.save(str(_x)+str(_y)+".png") img = ImageTool.pilImage_to_wxImage(im) bmp = wx.BitmapFromImage(img) il_max = il.Add(bmp) # create the list control # 创建列表窗口部件 self.list = wx.ListCtrl(self, -1, style=wx.LC_ICON | wx.LC_AUTOARRANGE) # assign the image list to it self.list.AssignImageList(il, wx.IMAGE_LIST_NORMAL) # create some items for the list # 为列表创建一些项目 for x in range(25): img = x % (il_max + 1) self.list.InsertImageStringItem(x, "%02d" % x, img)
def LoadBackground(self): global Background print('background') fnametmp = QFileDialog.getOpenFileName(self, 'Open file', './') fname = fnametmp[0] print("filename", fname) Background = imgtl.Load(fname) Refresh()
def LoadImage(self): global Image print('loading image...') fnametmp = QFileDialog.getOpenFileName(self, 'Open file', './') fname = fnametmp[0] print("filename", fname) Image = imgtl.Load(fname) Refresh()
def getData(inteIma, blockInfo, getRange, features): #inteIma 是积分图 #blockInfo是上一帧目标位置第一块的信息 #getRange是搜索范围信息 #features是在每个块的哪个位置建立的特征值。这是个二维数组,第一维是每个随机蕨,第二位是随机蕨中每个特征值 originlenth = blockInfo['lenth'] originWidth = blockInfo['width'] blocks = [] tureFeats = [] dataMats = [] #每个检测块的数据 for magnification in range(-10, 11): #对于块的浮动大小。长宽从缩小10%到放大10% lenth = int(originlenth * (1 + (magnification / 100))) # 块的长计算 width = int(originWidth * (1 + (magnification / 100))) # 块的宽计算 #print(originlenth,lenth) if magnification > -10: #第一取样(第一次循环)时不判断 if lenth == blocks[-1]['lenth'] and width == blocks[-1]['width']: continue #前后两次取样长宽差别太小(相差不足1),跳过 #print("长要搜索",len(range(getRange[0], getRange[1]-lenth+1))) x = getRange[0] while x <= getRange[1] - lenth + 1: #for x in range(getRange[0], getRange[1]-lenth+1): # 对于起点横坐标从开始到结束 #print("宽要搜索",len(range(getRange[2], getRange[3]-width+1))) y = getRange[2] while y <= getRange[3] - width + 1: #for y in range(getRange[2], getRange[3]-width+1): # 对于起始位置纵坐标,从开始到结束。块的起点位置确定完毕。 dataMat = [] # 一个块里建多个蕨。里面装的是data #print("搜索随机蕨的个数:",len(features)) block = {} block['x'] = x block['y'] = y block['lenth'] = lenth block['width'] = width #块的基本信息 blocks.append(block) for featurelist in features: #对于同一个块上不同的随机蕨. # 从特征的相对位置到实际位置转换(不完全) tureFeat = lt.getFeature(featurelist, block) #计算特征值 #print(tureFeat) #print() data = [] # 每个蕨里的特征数据,按顺序排列,顺序与特征位置数组相同 #print("搜索每个蕨特征的个数:",len(tureFeat)) for feature in tureFeat: # 对于一个随机蕨的不同特征 value = it.towBitBP(inteIma, block['x'] + feature['x'], block['y'] + feature['y'], feature['lenth'], feature['width']) data.append(value) dataMat.append(data) dataMats.append(dataMat) #此处dataMat第一维是每个块(此处应理解为示例),第二维是每个随机蕨,第三维是蕨内容 y += int(width * 0.1) x += int(lenth * 0.1) #print(dataMats) return dataMats, blocks
def getDataTem(inteIma, features, blocksInfo): dataMats = [] for blockInfo in blocksInfo: #对于每个块 dataMat = [] for featurelist in features: #下面这四行我自己看着都晕,慢慢琢磨吧。 tureFeat = lt.getFeature(featurelist, blockInfo) data = [] for feature in tureFeat: value = it.towBitBP(inteIma, blockInfo['x'] + feature['x'], blockInfo['y'] + feature['y'], feature['lenth'], feature['width']) data.append(value) dataMat.append(data) dataMats.append(dataArray) return dataMats
def update_figure(self): global ImageDisplayed self.ax0.cla() self.axx.cla() self.axy.cla() self.ax0.imshow(ImageDisplayed, aspect='auto', cmap=beam_map, origin='lower') projx, projy = ImageDisplayed.sum(axis=0), ImageDisplayed.sum(axis=1) x = np.arange(len(projx)) y = np.arange(len(projy)) if FLAG_fit > 0: p2X = imgtl.FitProfile(projx, x) p2Y = imgtl.FitProfile(projy, y) # # top plot self.axx.plot(projx) if FLAG_fit > 0: self.axx.plot(x, imgtl.dg(x, p2X), 'r--', linewidth=3) self.axx.set_xlim(self.ax0.get_xlim()) # # Right plot self.axy.plot(projy, range(len(projy))) if FLAG_fit > 0: self.axy.plot(imgtl.dg(y, p2Y), y, 'r--', linewidth=3) self.axy.set_ylim(self.ax0.get_ylim()) # Remove tick labels nullfmt = ticker.NullFormatter() self.axx.xaxis.set_major_formatter(nullfmt) self.axx.yaxis.set_major_formatter(nullfmt) self.axy.xaxis.set_major_formatter(nullfmt) self.axy.yaxis.set_major_formatter(nullfmt) self.draw()
eclick.ydata, erelease.ydata = erelease.ydata, eclick.ydata if eclick.xdata > erelease.xdata: eclick.xdata, erelease.xdata = erelease.xdata, eclick.xdata print(eclick.xdata, eclick.ydata, erelease.xdata, erelease.ydata) # fig.canvas.draw() bbox = np.array([ int(eclick.xdata), int(eclick.ydata), int(erelease.xdata), int(erelease.ydata) ]) return (bbox) Filename = "./data_samples/vc.dat" X, dx, dy, Nframes = imtl.LoadAWA(Filename) print("Dx,Dy,NFrames= ", dx, dy, Nframes) # sum m all the frame arr = imtl.DesInterlace(np.sum(X, axis=2)) fig = plt.figure() ax = fig.add_subplot(111) print("select bounding box for signal and press Q") plt_image = plt.imshow(arr) toggle_selector.RS = widgets.RectangleSelector(ax, onselect_getroi, drawtype='box', rectprops=dict(facecolor='red', edgecolor='red',
#以下是循环和循环要用的变量的初始化了 StanPosition =ut.getPosition(path) #从标准位置文件中获取目标真实位置 CenterError =[] blockSorted = [] # 块按概率排序的列表,八个块都在里面 targetPosition = [] #记录追踪过程中目标位置的序列 targetPosition.append(target) blockClassifier = [] # 每个块已训练好的的强分类器(adaboost分类器) offsetInfo = [] # 维护分块的偏移信息,所有示例的值都相同,并且不需要重置 features = [] imaIndex=0 centerErr=[] for image in images: #对于每一帧 imaIndex+=1 blocksInfos = [] # 维护示例的分块信息,每帧需要重置。第一维是示例,第二维是块 imaMat = it.image2Mat(imagePath+'/'+image,color) #图像转矩阵 inteIma = it.getInteIma(imaMat) #积分图 if image == '0001.jpg': #第一帧只学习,不分类,单独拿出来 originIndex = 0 posBag = it.getPosBag(X,Y,lenth,width) #正包 lables =list(np.ones(len(posBag))) #正包标签 negBag = it.getNegBag(X,Y,lenth,width,2,4) #负包 lables.extend(np.zeros(len(negBag))) #整个标签 #上面两个都是二位列表,blocksInfos[0][0][x]是第一个示例的第一个块的起始坐标的x值 for instance in posBag: #对于每个正示例分块并存储。这个循环只能干这么点事 # 分块,第一帧就用target了,没用targetPosition[-1] blocksInfo, offsetInfo = it.imageFrag( instance['x'], instance['y'], instance['lenth'], instance['width'], 2, 4)
plt.axis('off') # compute profiles histx, histy, x, y = imgtl.GetImageProjection(IMGt,cal) # plt.figure() plt.subplot(2,2,4) x=x-x[np.argmax(histx)] y=y-y[np.argmax(histy)] plt.plot (x,histx,'-') plt.plot (y,histy,'-') plt.xlabel ('distance') plt.ylabel ('population') plt.title('profiles::'+FilenameBeam,fontsize=FTsize) plt.show() # RMS calculations: imgtl.stats1d(x, histx) imgtl.stats1d(y, histy) imgtl.stats2d(x,y,IMGt) norm0, meanx0, meany0, meanI0, stdx0, stdy0, stdI0, correl0, Wx0, Wy0, averImage0, IMGf = \ imgtl.window_scan2dthreshold(IMGt, 1., 50, 0.00) plt.figure() plt.subplot (2,2,1) plt.plot (Wx0, averImage0,'o') plt.subplot (2,2,2) plt.plot (Wx0, stdx0,'ro') plt.plot (Wx0, stdy0,'go') plt.subplot (2,2,3) plt.plot (Wx0, correl0,'ro')
filenameBk = sys.argv[2] print("background file: "+filenameBk) Xi = pyl.imread(filenameIm) Xb = pyl.imread(filenameBk) X=Xi-Xb Xc=imgtl.RemoveEdge(X, 0) plt.imshow(Xc) norm0, meanx0, meany0, meanI0, stdx0, stdy0, stdI0, correl0, Wx0, Wy0, averImage0, IMGf = \ imgtl.window_scan2dthreshold(Xc, 1., 50, 0.00) plt.figure() plt.subplot (2,2,1) plt.plot (Wx0, averImage0,'o') plt.subplot (2,2,2) plt.plot (Wx0, stdx0,'ro') plt.plot (Wx0, stdy0,'go') plt.subplot (2,2,3) plt.plot (Wx0, correl0,'ro') plt.subplot (2,2,4)
width = 98 target = {} # 记录一帧中目标位置,放在track里 target['x'] = X target['y'] = Y target['lenth'] = lenth target['width'] = width targetPosition = [] # 记录追踪过程中目标位置的序列 targetPosition.append(target) numFeat = 4 numFern = 10 testX = 121 testY = 61 testLenth = 77 testWidth = 93 imaMat = it.image2Mat(imagePath + '/' + "0001.jpg", 1) inteIma = it.getInteIma(imaMat) posBag = it.getPosBag(X, Y, lenth, width) # 正包 lables = list(np.ones(len(posBag))) # 正包标签 negBag = it.getNegBag(X, Y, lenth, width, 1, 1) # 负包 lables.extend(np.zeros(len(negBag))) # 整个标签 offsetInfo = [] # 这个是块偏移信息,放外面 #print(allInstance) blocksInfos = [] # 每个块的信息,这里一幅图就是一个块。 blockClassifier = [] # 每个块已训练好的的强分类器(adaboost分类器) blockInfos = posBag.extend(negBag) blocksInfos.append(blockInfos) #为了使用以前写的randomFen函数,而这么搞的 randomFerns, dataMats, features = lt.randomFern(
import ImageTool as imtl import numpy as np import pylab as pyl import matplotlib.pyplot as plt import pydefaults # directory upperfile = "/Users/piot/ASTA_commissioning/quadscan/X121_20150601//tight_focus/" filename = "nml-2015-06-01-2205-23-13076.png" # in um/pixel cal = 9. thres = 0.02 A = imtl.Load(upperfile + filename) B = imtl.AutoCrop(A, 100) C = imtl.Threshold(B, thres) #imtl.DisplayCalibrated(B, cal) imtl.DisplayCalibratedProj(B, cal, 0.3) plt.xlabel('x ($\mu$m)', fontsize=24) plt.ylabel('y ($\mu$m)', fontsize=24) plt.title(filename, fontsize=24) plt.tight_layout() plt.show()
import numpy as np import time import os import scipy.optimize import math import matplotlib.pyplot as plt import ImageTool as imtl import AWA_tool as awa Filename = "./data_samples/vc.dat" cal = 0.039 # mm per pixel X, dx, dy, Nframes = imtl.LoadAWA(Filename) print("Dx,Dy,NFrames= ", dx, dy, Nframes) # sum m all the frame X_all_frame = imtl.DesInterlace(np.sum(X, axis=2)) TT = imtl.MouseCrop(X_all_frame) centers = imtl.ImageCenter(TT) print('center=', centers) plt.figure() #imtl.DisplayImage(X_all_frame) #plt.subplot (2,2,1) #imtl.DisplayCalibratedProj(X_all_frame, cal, 0.3) # #plt.subplot (2,2,2) #imtl.DisplayCalibratedProj(imtl.Crop(X_all_frame,centers, [200,200]), cal, 0.3) #plt.subplot (2,2,3)
# parameters bbox = 200 cal = 1 fudge = 0.3 threshold = 0. # scan over the number of data point # fileonly = rootname+"-"+str(1+i)+".png" # filename = UpperDir+"/"+SubDir+"/"+fileonly filenameBeam = FileDir + FilenameBeam filenameBkgd = FileDir + FilenameBkgd # load the image if test == 0: IMGbeam = imgtl.Load(filenameBeam) IMGbkgd = imgtl.Load(filenameBkgd) IMG = 1. * IMGbeam - IMGbkgd # IMG=ndimage.gaussian_filter(IMGT, 2) # ndimage.gaussian_filter(IMGT, sigma=3) if test == 1: # this makes a test image # a gaussian curve # IMG = 10.+np.random.rand((1296,1606)) IMGT = np.zeros((1296, 1606)) BKGD = np.zeros((1296, 1606)) IMG = np.zeros((1296, 1606)) s = np.shape(IMG) v = np.linspace(0, s[0], s[0]) h = np.linspace(0, s[1], s[1])
width = 98 target = {} #记录一帧中目标位置,放在track里 target['x'] = X target['y'] = Y target['lenth'] = lenth target['width'] = width targetPosition = [] #记录追踪过程中目标位置的序列 targetPosition.append(target) numFeat = 4 numFern = 12 testX = 121 testY = 61 testLenth = 77 testWidth = 93 imaMat = it.image2Mat(imagePath + '/' + "0001.jpg", 1) inteIma = it.getInteIma(imaMat) posBag = it.getPosBag(X, Y, lenth, width) #正包 lables = list(np.ones(len(posBag))) #正包标签 negBag = it.getNegBag(X, Y, lenth, width, 2, 4) #负包 lables.extend(np.zeros(len(negBag))) #整个标签 #负包并不是以整个图片出现的,而是以同一个块的组合出现,使每个块都学习到相同的 offsetInfo = [] #这个是块偏移信息,放外面 #print(allInstance) blocksInfos = [] blockClassifier = [] # 每个块已训练好的的强分类器(adaboost分类器) for instance in posBag: #对于每个正示例分块并存储。这个循环只能干这么点事。 # 分块,第一帧就用target了,没用targetPosition[-1]
filenameBk = sys.argv[2] print("background file: "+filenameBk) Xi = pyl.imread(filenameIm) Xb = pyl.imread(filenameBk) X=Xi-Xb Xc=imgtl.RemoveEdge(X, 0) plt.imshow(Xc) IMGf=imgtl.AutoCrop(Xc, 2000) histx, histy, x, y = imgtl.GetImageProjection(IMGf,cal) x=x-x[np.argmax(histx)] y=y-y[np.argmax(histy)] p2X= imgtl.FitProfile(histx, x) p2Y= imgtl.FitProfile(histy, y) print("fitX: ", p2X) print("fitY: ", p2Y) plt.figure()
def image_moments(data, semiaxis_a, semiaxis_b): global radius0 radius0 = (semiaxis_a + semiaxis_b) / 2 global semi_a0, semi_b0 semi_a0 = int(2 * semiaxis_a) semi_b0 = int(2 * semiaxis_b) print "Inital mask radius: ", radius0 h, v = data.shape[:2] global step step = int((h / 2 - max(semi_a0, semi_b0)) / m) print "Step size is: ", step #Retrieve cov(R) data cov_array = covR(data) #Find the image center-of-mass xbar, ybar, cov = image_raw_moments(data) center = [xbar, ybar] p2x, p2y = imtl.ImageFit(data, 1.0) print "Image center is at: ", p2x[0], p2y[0] center = [p2x[0], p2y[0]] # ellipse = data.copy() # mask_ellipse = create_elliptical_mask(h,v,center,radius0,3*radius0,45.0) # ellipse[~mask_ellipse] = 0 # plt.figure() # plt.imshow(ellipse) # plt.show() #Calculate the correct radii for <xx>,<yy> and <xy> moments. The condition is min(d covR(R) / dR) # m = len(cov_array) #Retrieve the positions of max(d covR(R) / dR) # nx, ny, nxy = dcov_array_max(cov_array) #Radius is calculated as the location of derivative minimum # radiusX = radius0 + step*np.argmin(np.gradient(cov_array[nx:m-1,0])) + step*nx # radiusY = radius0 + step*np.argmin(np.gradient(cov_array[ny:m-1,3])) + step*ny # radiusXY = radius0 + step*np.argmin(np.abs(np.gradient(cov_array[nxy:m-1,1]))) + step*nxy minx, miny, minxy = dcov_array_min(cov_array) semi_aX = semi_a0 + step * minx semi_bX = semi_b0 + step * minx semi_aY = semi_a0 + step * miny semi_bY = semi_b0 + step * miny semi_aXY = semi_a0 + step * minxy semi_bXY = semi_b0 + step * minxy print "Mask ellipse X: ", semi_aX, semi_bX print "Mask ellipse Y: ", semi_aY, semi_bY print "Mask ellipse XY: ", semi_aXY, semi_bXY #Plotting covariance matrix elements for debugging plot_covarray(cov_array) #Create masks for <xx>,<yy> and <xy> moments maskX = create_elliptical_mask(h, v, center, semi_aX, semi_bX, skew) maskY = create_elliptical_mask(h, v, center, semi_aY, semi_bY, skew) maskXY = create_elliptical_mask(h, v, center, semi_aXY, semi_bXY, skew) #Prepare three copies of masked data for final moments calculation tempX = data.copy() tempY = data.copy() tempXY = data.copy() tempX[~maskX] = 0 tempY[~maskY] = 0 tempXY[~maskXY] = 0 # plt.figure() fig, ax = plt.subplots(1) extent = (0, len(tempXY[:, 0]), 0, len(tempXY[:, 1])) tempXY = np.flip(tempXY, 0) ax.imshow(imtl.Normalize(tempXY), extent=extent) cx = patches.Ellipse(center, 2 * semi_aX, 2 * semi_bX, skew, color='y', linewidth=3, fill=False) cy = patches.Ellipse(center, 2 * semi_aY, 2 * semi_bY, skew, color='g', linewidth=3, fill=False) cxy = patches.Ellipse(center, 2 * semi_aXY, 2 * semi_bXY, skew, color='m', linewidth=3, fill=False) ax.add_patch(cx) ax.add_patch(cy) ax.add_patch(cxy) plt.legend((cx, cy, cxy), (r'Mask $\langle xx \rangle$', r'Mask $\langle yy\rangle$', r'Mask $\langle xy\rangle$')) plt.xlabel('x (px)') plt.ylabel('y (px)') plt.tight_layout() plt.show() #Final calculation xxt, yyt, covx = image_raw_moments(tempX) xxt, yyt, covy = image_raw_moments(tempY) xxt, yyt, covxy = image_raw_moments(tempXY) return covx[0, 0], covy[1, 1], covxy[0, 1]
for i in range(NPoints): filenameX = UpperDir + "/" + SubDir + "/" + rootname + "_" + str(i) + "_x" filenameY = UpperDir + "/" + SubDir + "/" + rootname + "_" + str(i) + "_y" # load the save histograms histX = np.loadtxt(filenameX) histY = np.loadtxt(filenameY) # create the horizontal coordinate axisX = np.arange(len(histX)) axisY = np.arange(len(histY)) # center the histogram and select a region of interest (ROI) around the peak window = 1000. histXc, axisXc = imgtl.center_and_ROI(histX, axisX, window) histYc, axisYc = imgtl.center_and_ROI(histY, axisY, window) # remove background (there are many way of doing this) window = 10 histXc, axisXc = imgtl.removebackground(histXc, axisXc, window) histYc, axisYc = imgtl.removebackground(histYc, axisYc, window) p2X = imgtl.FitProfile(histXc, axisXc) p2Y = imgtl.FitProfile(histYc, axisYc) print("fitX: ", p2X) print("fitY: ", p2Y) plt.figure() plt.plot(axisXc, histXc, 'ob', alpha=0.1)
for i in range (NPoints): filenameX= UpperDir+"/"+SubDir+"/"+rootname+"_"+str(i)+"_x" filenameY= UpperDir+"/"+SubDir+"/"+rootname+"_"+str(i)+"_y" # load the save histograms histX=np.loadtxt(filenameX) histY=np.loadtxt(filenameY) # create the horizontal coordinate axisX=np.arange(len(histX)) axisY=np.arange(len(histY)) # center the histogram and select a region of interest (ROI) around the peak window=1000. histXc, axisXc = imgtl.center_and_ROI(histX, axisX, window) histYc, axisYc = imgtl.center_and_ROI(histY, axisY, window) # remove background (there are many way of doing this) window = 10 histXc, axisXc = imgtl.removebackground(histXc, axisXc, window) histYc, axisYc = imgtl.removebackground(histYc, axisYc, window) p2X= imgtl.FitProfile(histXc, axisXc) p2Y= imgtl.FitProfile(histYc, axisYc) print "fitX: ", p2X print "fitY: ", p2Y
#A. Halavanau. DeKalb, IL (2017) / Menlo Park, CA (2018) import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import rotate import ImageTool as imtl from statistical import * from parameters import * i = 1 pwd = 'examples/Normal_quad_scan_L2/' filename = pwd + 'X111_YAG_' + str(i) + '_bkg_0.png' filenamebg = pwd + 'X111_YAG_' + str(i) + '_img_0.png' data = imtl.Load(filename) bg = imtl.Load(filenamebg) data = data - bg data = data[0:2000, 0:2000] data = imtl.Normalize(data) #experimental data_rot = data.copy() data_rot = rotate(data, skew, reshape=False) x, y = imtl.ImageFit(data_rot, 1.0, True) print "Image center is at: ", int(x[0]), int(y[0]) print "Gaussian fit sizes (px): ", int(x[2]), int(y[2]) print "Gaussian fit sizes (m): ", cal * x[2], cal * y[2] sigma_max = int(np.max((x[2], y[2]))) sigma_min = int(np.min((x[2], y[2])))