def get_calibration(fignum = 1, pct_wide = 0.2, pct_high = 0.33, tunneldicts=None):
	ax = pylab.figure(fignum).axes[0]
	ymax = round(ax.get_ybound()[1])
	xmax = round(ax.get_xbound()[1])
	pix_wide = ymax*pct_wide
	pix_high = ymax*pct_high
	print >> sys.stderr, 'image is %s x %s; windows will be %s, %s' % (xmax,ymax,pix_wide,pix_high)
	cm_dists = []
	print >> sys.stderr, 'click 0, 1, 10 cm marks'
	pylab.xlim(0,pix_high)
	pylab.ylim(ymax,ymax-pix_wide)
	p0,p1,p10 = pylab.ginput(3,0)
	cm_dists.append(vidtools.hypotenuse(p0,p1))
	cm_dists.append(vidtools.hypotenuse(p0,p10)/10.0)
	print >> sys.stderr, 'click 0, 1, 10 cm marks'
	pylab.xlim(xmax-pix_wide,xmax)
	pylab.ylim(pix_high,0)
	p0,p1,p10 = pylab.ginput(3,0)
	cm_dists.append(vidtools.hypotenuse(p0,p1))
	cm_dists.append(vidtools.hypotenuse(p0,p10)/10.0)
	print >> sys.stderr, 'click bolt 1'
	pylab.xlim(0,pix_wide)
	pylab.ylim(ymax,ymax-pix_wide)
	horiz = [pylab.ginput(1,0)[0]]
	print >> sys.stderr, 'click bolt 2'
	pylab.xlim(xmax-pix_wide,xmax)
	pylab.ylim(ymax,ymax-pix_wide)
	horiz.append(pylab.ginput(1,0)[0])
	pylab.xlim(0,xmax)
	pylab.ylim(ymax,0)
	if tunneldicts is not None:
		tunneldicts['cm_pts'] = cm_dists
		tunneldicts['horiz'] = horiz
	else:
		return cm_dists,horiz
Esempio n. 2
0
    def acquire_masks(self):
        im1 = self.cam2.get()
        pl.imshow(im1, cmap='gray')
        pl.title('Select Eye')
        pts_eye = pl.ginput(n=0, timeout=0)
        pts_eye = np.array(pts_eye, dtype=np.int32)
        mask_eye = np.zeros(im1.shape, dtype=np.int32)
        cv2.fillConvexPoly(mask_eye, pts_eye, (1,1,1), lineType=cv2.LINE_AA)

        pl.clf()
        
        im2 = self.cam2.get()
        pl.imshow(im2, cmap='gray')
        pl.title('Select Wheel')
        pl.gcf().canvas.draw()
        pts_wheel = pl.ginput(n=0, timeout=0)
        pts_wheel = np.array(pts_wheel, dtype=np.int32)
        mask_wheel = np.zeros(im2.shape, dtype=np.int32)
        cv2.fillConvexPoly(mask_wheel, pts_wheel, (1,1,1), lineType=cv2.LINE_AA)

        pl.close()

        self.mask = np.array([mask_eye, mask_wheel])
        self.mask_flat = self.mask.reshape((2,-1))
        return self.mask
Esempio n. 3
0
    def splitTrial(self, baseChannel):
        self.baseChannel = baseChannel

        self.ax.plot(self.rawData[self.baseChannel])
        numElements = self.rawData.shape[0]

        self.ax1 = plt.axes([0.0, 0.5, 0.1, 0.075])
        self.b1 = Button(self.ax1, 'Submit')
        self.b1.on_clicked(self.onSubmit)

        begin = ginput(1)
        end = ginput(1)

        length = int(end[0][0] - begin[0][0])

        self.iBegins = [int(begin[0][0]) + i * length for i in xrange(self.numTrials)]
        self.iEnds = [int(begin[0][0]) + (i + 1) * length - 1 for i in xrange(self.numTrials)]



        [minL, maxL] = getYValueLimits(self.rawData, self.baseChannel)
        for iLine in xrange(self.numTrials):
            self.endlines.append(self.ax.axvline(self.iEnds[iLine], 0, maxL, color='k', picker=5))
            self.fig.canvas.mpl_connect('pick_event', self.onPick)
            self.fig.canvas.mpl_connect('key_press_event', self.onKey)

        # self.fig.canvas.draw()
        plt.show()
Esempio n. 4
0
def wait(msg=None):
    """Wait for the user to acknowledge the plot."""
    import pylab
    #from matplotlib.blocking_input import BlockingInput

    if msg: print msg

    #block = BlockingInput(fig=pylab.gcf(), eventslist=('key_press_event',))
    #block(n=1, timeout=-1)
    pylab.ginput()
Esempio n. 5
0
def plotgrid(data,d=10,shape=(30,30)):
    """Plot a list of images on a grid."""
    ion()
    gray()
    clf()
    for i in range(min(d*d,len(data))):
        subplot(d,d,i+1)
        row = data[i]
        if shape is not None: row = row.reshape(shape)
        imshow(row)
    ginput(1,timeout=0.1)
Esempio n. 6
0
def touch_with_func():
    plot_data = {}
    read_data = CVMCv1Parser.from_file('cv1.txt')
    for i in range(0, 1):
        data = read_data.data[i]['data']
        temp = read_data.data[i]['temp']
        data.set_free_energy_00_from_logtxt('log.txt')
        data.set_end_energy(0, 0)
        err = make_err_func(func)

        points = []
        for j in range(15):
            pylab.plot(data['comp1'], data['corrected_g'], '+')
            pylab.axvline(x=1/16*(j+1), color='black')
            try:
                p = pylab.ginput(n=1, timeout=2)
                while p == []:
                    p = pylab.ginput(n=1, timeout=2)
                print(1/16*(j+1), p[0][1])
            except KeyboardInterrupt:
                print("座標習得を諦めました")
                exit()
            points.append(p[0])
            pylab.close()
        points = np.array(points)

        param = optimize.leastsq(
            err, [1, 1, 1, 1, 1], args=(points[:, 0],
                                        points[:, 1]))[0]
        judge = np.abs(err(param, data['comp1'], data['corrected_g'])) < 1
        inliersx = data['comp1'][judge]
        inliersy = data['corrected_g'][judge]
        x = inliersx
        y = inliersy
        opt = optimize.leastsq(
            err, [1, 1, 1, 1, 1], args=(x, y))[0]
        fitx = np.linspace(0, 1, 100)
        fity = func(opt, fitx)

        plot_data.update({temp:[data['comp1'], data['corrected_g'], fitx, fity]})
    i = 1
    for temp in plot_data:
        pd = plot_data[temp]
        d = (33 // (len(plot_data) + 1))
        pylab.plot(pd[0], pd[1], '+',
                   color=COLOR_PALETTE[d*i][1])
        pylab.plot(pd[2], pd[3], color=COLOR_PALETTE[d*i][0], linewidth=2)
        save_results(temp, pd)
        i += 1
    pylab.xlim(0, 1)

    pylab.show()
Esempio n. 7
0
def wincoord(winno):
	cor1 = 1 ; cor2 = 0
	while cor1 > cor2:
		print("Please click at the start (left-side) of the window %d" % (winno))
		cor1 = plt.ginput(1)[0][0]
		print(cor1)
		print("Please click at the end (right-side) of the window %d" % (winno))
		cor2 = plt.ginput(1)[0][0]
		print(cor2)
		if cor1 > cor2:
			#print('pixel coordinates of the start of the window is greater than the end! So lets restarts input for window ' % (winno)) 
			# Check if coordinates were entered in Arabic fashion! Swap if needed.
			cor1, cor2 = cor2, cor1
	return round(cor1,0),round(cor2,0)
Esempio n. 8
0
    def get_terminus(self):
        from matplotlib.widgets import Cursor

        if self.mask_computed == True:
            self.mask = dbg.initialize_mask(self.thk)

            plt.clf()
            plt.pcolormesh(self.x, self.y, self.mask)
            plt.contour(self.x, self.y, self.z, colors='black')
            plt.axis('tight')
            plt.axes().set_aspect('equal')
            plt.draw()

        plt.setp(plt.gca(),autoscale_on=False)

        cursor = Cursor(plt.axes(), useblit=True, color='white', linewidth=1 )

        if self.ph is not None and self.mask_computed == False:
            for p in self.ph:
                p.remove()
            self.ph = None

        pts = []
        while len(pts) < 4:
            pts = np.asarray( plt.ginput(4, timeout=-1) )

        self.ph = plt.fill(pts[:,0], pts[:,1], 'white', lw = 2, alpha=0.5)
        plt.draw()

        self.pts = pts

        self.mask_computed = False
Esempio n. 9
0
	def _Delete_spectra_fired(self):
		plt.figure()
		plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
		plt.title('Pick between times to delete (top to bottom)')
		plt.xlabel('Wavelength')
		plt.ylabel('Time')
		fittingto = np.array(ginput(2))
		plt.show()
		plt.close()

		index_time_top=(np.abs(Data.time-fittingto[1,1])).argmin()
		index_time_bottom=(np.abs(Data.time-fittingto[0,1])).argmin()+1

		if index_time_bottom <= index_time_top:
			hold = index_time_top
			index_time_top = index_time_bottom
			index_time_bottom = hold

		if index_time_top == 0:
			Data.TrA_Data = Data.TrA_Data[index_time_bottom:,:]
			Data.time = Data.time[index_time_bottom:]

		if index_time_bottom == Data.time.shape:
			Data.TrA_Data = Data.TrA_Data[:index_time_top,:]
			Data.time = Data.time[:index_time_top]

		if index_time_top != 0 & index_time_bottom != Data.time.shape:
			Data.TrA_Data = np.vstack((Data.TrA_Data[:index_time_top,:],Data.TrA_Data[index_time_bottom:,:]))
			Data.time = np.hstack((Data.time[:index_time_top],Data.time[index_time_bottom:]))

		self.log = "%s \nDeleted spectra between %s and %s" %(self.log,fittingto[0,1],fittingto[1,1])
Esempio n. 10
0
    def etch(self, refmask=[0]):
        """Cut away at surface. Can only click polygons for now.
        Optionally input reference mask to guide etching.
        """

        size = self.size
        mask = n.ones((self.size,self.size), dtype='bool')

        print 'Click for points of region to etch (right click to exit).'
        p.figure(1)
        if len(refmask) != 1:
            p.imshow(n.transpose(-refmask), aspect='auto', origin='lower', interpolation='nearest', cmap=p.cm.Greys, extent=(0,1,0,1), vmax=0.5)
        else:
            p.imshow(n.transpose(-self.mask), aspect='auto', origin='lower', interpolation='nearest', cmap=p.cm.Greys, extent=(0,1,0,1), vmax=0.5)
        xy = p.ginput(n=0, timeout=3000)
        xy = n.array(xy)
        
        print 'Calculating remaining region...'
        p.figure(1)
        p.axis([0,1,0,1])
        p.fill(xy[:,0],xy[:,1],'k')

        for i in range(size):
            for j in range(size):
                mask[i,j] = not(point_inside_polygon(float(i)/size, float(j)/size, xy))
        self.mask = self.mask * mask
    def select_valid_region_topView(frame_input):
        inputFig = plt.figure()
        plt.title('Select points to define valid regions:top View')    
        plt.imshow(frame_input, cmap = 'gray', interpolation = 'bicubic')
        # Same as ginput() in Matlab 
        region_ptList = ginput(8)
        plt.close(inputFig)
    
        region_ptArray0 = np.asarray(region_ptList)
        region_ptArray = region_ptArray0.astype(int)
        region_ptArray = np.vstack((region_ptArray, region_ptArray[0,:]))
    
        # Get the arms A,B,C,U
        pointsLeft = region_ptArray[0:4,:]
        maskLeft0 = np.zeros(frame_input.shape[:2],dtype = 'uint8')
        cv2.drawContours(maskLeft0,[pointsLeft],0,255,-1)
        maskLeft0 = cv2.cvtColor(maskLeft0,cv2.COLOR_GRAY2BGR)
        maskLeft = cv2.cvtColor(maskLeft0,cv2.COLOR_BGR2GRAY)
 
        pointsRight = region_ptArray[4:8,:]
        maskRight0 = np.zeros(frame_input.shape[:2],dtype = 'uint8')
        cv2.drawContours(maskRight0,[pointsRight],0,255,-1)
        maskRight0 = cv2.cvtColor(maskRight0,cv2.COLOR_GRAY2BGR)
        maskRight = cv2.cvtColor(maskRight0,cv2.COLOR_BGR2GRAY)
        
        return maskLeft0, maskLeft, maskRight0, maskRight
Esempio n. 12
0
def selectPoints(im1_path, im2_path):
	im = Image.open(im1_path)
	plt.imshow(im)
	counter, f_points = constant.TOTAL_FEATURE, []
	while counter != 0:
		print "Click on screen!"
		x = ginput(1)
		counter -= 1
		f_points.append([x[0][0], x[0][1]])
		plt.scatter(x[0][0], x[0][1])
		plt.draw()
		print("Clicked point at ", x, " | Clicks left: ", counter)
	plt.show()
	second_points = drag_control_points(mpimg.imread(im2_path), np.array(f_points))
	
	intermediate_feature = interpolatePts(combinePoints(f_points, second_points))
	frames = combineImages(intermediate_feature, constant.TRIANGLES, im1_path, im2_path)
	frames.extend(frames[::-1])
	# otherone = [cv2.cvtColor(items, cv2.COLOR_RGB2BGR) for items in frames]
	# writeGif("lol.GIF", otherone, duration=0.07)
	while True:
		for i in range (0, len(frames)): 
			f = frames[i]
			cv2.waitKey(20) 
			cv2.imshow("Cameras",f) 
			cv2.waitKey(20)
Esempio n. 13
0
def Main():
    save_file_root = "C:\\Users\\Camera\\Desktop\\Video_Editing_Tools\\Analysis\\Set 8\\Limb_Movement"
    load_video_filename = "C:\\Users\\Camera\\Desktop\\Video_Editing_Tools\\Analysis\\Set 8\\Median.avi"
    # load_video_filename = "C:\\Users\\Camera\\Desktop\\GtHUb\\Two-Cameras\\Data\\AG052014-01\\21072014\\Trial5\\PS3_Vid83.avi"

    cap = cv2.VideoCapture(load_video_filename)

    ret, prvs = cap.read()
    prvs = cv2.cvtColor(prvs, cv2.COLOR_BGR2GRAY)

    frames = int(cap.get(cv.CV_CAP_PROP_FRAME_COUNT))

    # Select mask in which we should look for the initial  good points to track - a.k.a. select limb to track
    pl.figure()
    pl.title("Select mask")
    pl.imshow(prvs, cmap=mpl_cm.Greys_r)
    pts = []
    while not len(pts):
        pts = pl.ginput(0)
    pl.close()
    path = mpl_path.Path(pts)
    mask = np.zeros(np.shape(prvs), dtype=np.uint8)
    for ridx, row in enumerate(mask):
        for cidx, pt in enumerate(row):
            if path.contains_point([cidx, ridx]):
                mask[ridx, cidx] = 1

    for n in range(frames):
        ret, next = cap.read()
        next = cv2.cvtColor(next, cv2.COLOR_BGR2GRAY)
        flow = cv2.calcOpticalFlowFarneback(prvs, next, 0.5, 3, 10, 3, 5, 1.2, 0)

        distt = 3
        threshold = 100
        new_mask = np.zeros(np.shape(prvs), dtype=np.uint8)
        for ridx, row in enumerate(mask):
            for cidx, pt in enumerate(row):
                if mask[ridx, cidx] == 1:
                    y = ridx + int(round(flow[ridx, cidx, 1]))
                    # print int(round(flow[ridx,cidx,1]))
                    x = cidx + int(round(flow[ridx, cidx, 0]))
                    if int(round(flow[ridx, cidx, 1])) < 10 and int(round(flow[ridx, cidx, 0])) < 10:
                        tmask = next[y - distt : y + distt + 1, x - distt : x + distt + 1]
                        # print tmask
                        idx = np.where(tmask > threshold)
                        # print idx[0]+y-distt
                        new_mask[idx[0] + y - distt, idx[1] + x - distt] = 1

        mask = new_mask
        next *= new_mask

        cv2.imwrite("C:\\Users\\Camera\\Desktop\\TEST.png", next)
        cv2.imshow("Limb", next)
        k = cv2.waitKey(30) & 0xFF
        if k == 27:
            break

    prvs = next
    cv2.destroyAllWindows()
    cap.release()
Esempio n. 14
0
	def _DeleteTraces_fired(self):
		plt.figure()
		plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
		plt.title('Pick between wavelength to delete (left to right)')
		plt.xlabel('Wavelength')
		plt.ylabel('Time')
		fittingto = np.array(ginput(2))
		plt.show()
		plt.close()

		index_wavelength_left=(np.abs(Data.wavelength-fittingto[0,0])).argmin()
		index_wavelength_right=(np.abs(Data.wavelength-fittingto[1,0])).argmin()+1


		if index_wavelength_right <= index_wavelength_left:
			hold = index_wavelength_left
			index_wavelength_left = index_wavelength_right
			index_wavelength_right = hold

		if index_wavelength_left == 0:
			Data.TrA_Data = Data.TrA_Data[:,index_wavelength_right:]
			Data.wavelength = Data.wavelength[index_wavelength_right:]

		if index_wavelength_right == Data.wavelength.shape:
			Data.TrA_Data = Data.TrA_Data[:,:index_wavelength_left]
			Data.wavelength = Data.wavelength[:index_wavelength_left]

		if index_wavelength_left != 0 & index_wavelength_right != Data.wavelength.shape:
			Data.TrA_Data = np.hstack((Data.TrA_Data[:,:index_wavelength_left],Data.TrA_Data[:,index_wavelength_right:]))
			Data.wavelength = np.hstack((Data.wavelength[:index_wavelength_left],Data.wavelength[index_wavelength_right:]))

		self.log = "%s \nDeleted traces between %s and %s" %(self.log,fittingto[0,0],fittingto[1,0])
Esempio n. 15
0
    def fit_and_plot(self, image):
        print "fit and plot"
        p = self.parameters.IonsOnCamera
        x_axis = np.arange(p.horizontal_min, p.horizontal_max + 1, self.image_region[0])
        y_axis = np.arange(p.vertical_min, p.vertical_max + 1, self.image_region[1])
        xx, yy = np.meshgrid(x_axis, y_axis)
        #import IPython
        #IPython.embed()

        #self.fitter.report(params)
        #ideally graphing should be done by saving to data vault and using the grapher
        #p = Process(target = self.fitter.graph, args = (x_axis, y_axis, image, params, result))
        #p.start()

        pylab.imshow(image)
        positions = pylab.ginput(0)
        positions = [x + np.min(x_axis) for x,y in positions]
        self.fitter = ion_state_detector(positions)
        result, params = self.fitter.guess_parameters_and_fit(xx, yy, image)
        self.fitter.graph(x_axis, y_axis, image, params, result)
        position_list = []

        try:
            i = 0
            while(True):
                position_list.append(params['pos'+str(i)].value)
                i += 1
        except KeyError:
            pass

        self.pv.set_parameter('IonsOnCamera','fit_background_level', params['background_level'].value)
        self.pv.set_parameter('IonsOnCamera','fit_amplitude', params['amplitude'].value)
        self.pv.set_parameter('IonsOnCamera','ion_positions', position_list) #TODO ?? FIXME
        self.pv.set_parameter('IonsOnCamera','ion_number', len(position_list)) #TODO ?? FIXME
        self.pv.set_parameter('IonsOnCamera','fit_sigma', params['sigma'].value)
Esempio n. 16
0
def get_terminus():
    from matplotlib.widgets import Cursor
    def tellme(s):
        print s
        plt.title(s,fontsize=16)
        plt.draw()

    plt.setp(plt.gca(),autoscale_on=False)

    cursor = Cursor(plt.axes(), useblit=True, color='white', linewidth=1 )

    happy = False
    while not happy:
        pts = []
        while len(pts) < 4:
            tellme('Select 4 corners of the terminus region')
            pts = np.asarray( plt.ginput(4, timeout=-1) )
            if len(pts) < 4:
                tellme('Too few points, starting over')
                time.sleep(1) # Wait a second

        ph = plt.fill(pts[:,0], pts[:,1], 'white', lw = 2, alpha=0.5)

        tellme('Done? Press any key if yes, mouse click to reset')

        happy = plt.waitforbuttonpress()

        # Get rid of fill
        if not happy:
            for p in ph: p.remove()

        return pts
Esempio n. 17
0
    def get_wavelimits(self, qrspeaks, leads=range(12)):
        """
        Given qrspeaks / point on qrs,
        interactively, obtain qrs onset, end and tend
        leads is a list of the indices of ECG leads
        """
        ax = pylab.subplot(111)
        ax.set_title("Pick QRS onset, end and T end")
        #ax = matplotlib.pyplot.axes()
        meanrr = int(scipy.mean(qrspeaks[1:] - qrspeaks[:-1]))
        onems = int(self.samplingrate / 1000)
        r = qrspeaks[int(len(qrspeaks) * 2/3)]  # choose a beat 2/3 of way
        
        start = r - 200 * onems  # 400 ms before
        end = start + meanrr

        for l in leads:
            ax.plot(self.data[start:end, l])

        cursor = Cursor(ax)

        pts = pylab.ginput(3)
        q, s, t = [pt[0] for pt in pts]
        #pylab.show()
        qrsonsets = qrspeaks + int(q - 200 * onems)
        qrsends = qrspeaks + int(s - 200 * onems)
        tends = qrspeaks + int(t - 200 * onems)
        return qrsonsets, qrsends, tends
Esempio n. 18
0
    def fit_and_plot(self, image):
        print "fit and plot"
        p = self.parameters.IonsOnCamera
        x_axis = np.arange(p.horizontal_min, p.horizontal_max + 1, self.image_region[0])
        y_axis = np.arange(p.vertical_min, p.vertical_max + 1, self.image_region[1])
        xx, yy = np.meshgrid(x_axis, y_axis)
        #import IPython
        #IPython.embed()

        #self.fitter.report(params)
        #ideally graphing should be done by saving to data vault and using the grapher
        #p = Process(target = self.fitter.graph, args = (x_axis, y_axis, image, params, result))
        #p.start()
        pylab.figure()
        pylab.imshow(image)
        pylab.show()
        pylab.figure()
        img_1d = np.sum(image, axis=0)
        pylab.plot(img_1d)
        threshold = pylab.ginput(0)
        threshold = threshold[0][1]
        print threshold

        ion_edges = self.isolate_ions(img_1d, threshold)
        centers = self.fit_individual_ions(img_1d, ion_edges)

        deltax = []
        for i, x in enumerate(ion_edges):
            try: deltax.append( centers[i+1] - centers[i] )
            except: pass
        pylab.figure()
        pylab.plot(deltax, 'o')
        pylab.show()
Esempio n. 19
0
def getCoordinate(direction='both',axh=None,fig=None):
  """Tool for selecting a coordinate, functionality similar to ginput for a single point. Finish with right mouse button."""
  if not axh:
    axh = pl.gca()
  if not fig: fig = pl.gcf()
  hor=False;ver=False
  if direction is 'horizontal' or 'hor' or 'both':
    hor=True
  if direction is 'vertical' or 'ver' or 'both':
    ver=True

  finished=False
  def button_press_callback(event):
    if event.inaxes:
      if event.button == 3:
        finished = True
  fig.canvas.mpl_connect('button_press_event', button_press_callback)
  print("Select a coordinate, finish with right click.")
  linh = []
  while not finished:
    for tlinh in linh:
      tlinh.remove()
      linh = []
    pl.draw()
    pos = pl.ginput(1)[0]
    if hor:
      linh.append(pl.axvline(pos[0]))
    if ver:
      linh.append(pl.axhline(pos[1]))
    pl.draw()
    pl.waitforbuttonpress()

  
  fig.canvas.draw()
  return pos
Esempio n. 20
0
def Set_Masks(Filename,number,message,save_name):
	Video = cv2.VideoCapture(Filename)
	height = int(Video.get(4))
	width = int(Video.get(3))
	frames = int(Video.get(cv.CV_CAP_PROP_FRAME_COUNT))
	FOURCC = cv2.cv.CV_FOURCC(*'XVID')
	color_names_RBG = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(255,0,255),(0,255,255),(0,0,0)] #BGR
	
	s,frame = Video.read()
	disp_frame = frame[:]
	frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
	
	Masks = np.zeros((number,height,width),dtype=np.uint8)
	
	for n in range(number):
		pl.figure()
		pl.title(message+" %i"%(n+1))
		pl.imshow(disp_frame, cmap=mpl_cm.Greys_r)
		pts = []
		while not len(pts):
			pts = pl.ginput(0)
		pts = np.array(pts, dtype=np.int32)
		pl.close()
		path = mpl_path.Path(pts)
		for ridx,row in enumerate(frame):
			for cidx,pt in enumerate(row):
				if path.contains_point([cidx, ridx]):
					Masks[n,ridx,cidx] = 1
					
		cv2.polylines(disp_frame, [pts], 1, color_names_RBG[n%6], thickness=1) #BGR
		
	cv2.imwrite(save_name,disp_frame)
	Video.release()

	return Masks
Esempio n. 21
0
def ctc_align_targets(outputs,targets,threshold=100.0,verbose=0,debug=0,lo=1e-5):
    """Perform alignment between the `outputs` of a neural network
    classifier and some targets. The targets themselves are a time sequence
    of vectors, usually a unary representation of each target class (but
    possibly sequences of arbitrary posterior probability distributions
    represented as vectors)."""

    outputs = maximum(lo,outputs)
    outputs = outputs * 1.0/sum(outputs,axis=1)[:,newaxis]

    # first, we compute the match between the outputs and the targets
    # and put the result in the log domain
    match = dot(outputs,targets.T)
    lmatch = log(match)

    if debug:
        figure("ctcalign"); clf();
        subplot(411); imshow(outputs.T,interpolation='nearest',cmap=cm.hot)
        subplot(412); imshow(lmatch.T,interpolation='nearest',cmap=cm.hot)
    assert not isnan(lmatch).any()

    # Now, we compute a forward-backward algorithm over the matches between
    # the input and the output states.
    both = forwardbackward(lmatch)

    # We need posterior probabilities for the states, so we need to normalize
    # the output. Instead of keeping track of the normalization
    # factors, we just normalize the posterior distribution directly.
    epath = exp(both-amax(both))
    l = sum(epath,axis=0)[newaxis,:]
    epath /= where(l==0.0,1e-9,l)

    # The previous computation gives us an alignment between input time
    # and output sequence position as posteriors over states.
    # However, we actually want the posterior probability distribution over
    # output classes at each time step. This dot product gives
    # us that result. We renormalize again afterwards.
    aligned = maximum(lo,dot(epath,targets))
    l = sum(aligned,axis=1)[:,newaxis]
    aligned /= where(l==0.0,1e-9,l)

    if debug:
        subplot(413); imshow(epath.T,cmap=cm.hot,interpolation='nearest')
        subplot(414); imshow(aligned.T,cmap=cm.hot,interpolation='nearest')
        ginput(1,0.01);
    return aligned
Esempio n. 22
0
    def set_parameter(self, name, value):
        """
        This functions sets a parameter named "name" to a value.
        """

        try:
            # if we enter something like "min=x", get a click from the user
            if value in ['x','y']:
                # get the click
                print "Please click somewhere to get the "+value+" value."
                _st.raise_figure_window()
                click = _pylab.ginput()

                # use the click value.
                if    len(click)>0 and value=='x': value = click[0][0]
                elif  len(click)>0 and value=='y': value = click[0][1]
                else:
                    print "\nCLICK ABORTED.\n"
                    return

            elif value in ['dx', 'dy', 'slope']:
                # get two clicks
                print "Please click twice to use the "+value+" value."
                _st.raise_figure_window()
                clicks = _pylab.ginput(2)

                # make sure we got two clicks
                if len(clicks) == 2:
                    dx = clicks[1][0]-clicks[0][0]
                    dy = clicks[1][1]-clicks[0][1]
                    if value=='dx': value = dx
                    if value=='dy': value = dy
                    if value=='slope': value = dy/dx

                else:
                    print "\nCLICKS ABORTED.\n"
                    return


            i = self.pnames.index(name)
            self.p0[i] = float(value)
            return True

        except:
            print "ERROR:", name, "is not a valid variable or", value, "is not a valid value."
            return False
Esempio n. 23
0
def on_key(event):
    #print 'you pressed', event.key, event.xdata, event.ydata
    if   (event.key == 'q'):
        sys.exit(0)
    #
    elif (event.key == 'w'):
        pylab.close(event.canvas.figure)
    #
    elif (event.key == 'd'):
        print "##############################################################"
        print "Please click two points to get the distance and slope."
        from matplotlib.widgets import Cursor
        cursor = Cursor(event.inaxes, useblit=False, color='red', linewidth=1)
        points = pylab.ginput(n=2, show_clicks=True, timeout=0)
        xs  = pylab.array([points[0][0], points[1][0]])
        ys  = pylab.array([points[0][1], points[1][1]])
        dx = xs[1] - xs[0]
        dy = ys[1] - ys[0]
        dy_log = pylab.log10(ys[0]) - pylab.log10(ys[1])
        dy_ln = pylab.log(ys[0]) - pylab.log(ys[1])
        angle = pylab.arctan2(dy, dx)
        print "points = ", points
        print "distance (x) =", dx
        print "distance (y) =", dy
        print "distance =", pylab.sqrt( dx**2 + dy**2 )
        print "Ratio: x0/x1 =", xs[0] / xs[1], "   x1/x0 =", xs[1] / xs[0], "  y0/y1 =", ys[0] / ys[1], "  y1/y0 =", ys[1] / ys[0]
        print "dy/y0 = ", dy/ys[0]
        print "dx/x0 = ", dx/xs[0]
        print "Angle: theta = atan2(y/x) =", angle, "rad =", angle*180.0/pylab.pi, "deg"
        print "Slope: ", dy/dx, "  1/slope =", dx/dy
        print "Slope (log10 scale):", dy_log/dx
        print "Slope (ln scale):",    dy_ln/dx
        event.inaxes.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], '--r', lw=1.0)
        event.inaxes.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]],  '+r', lw=1.0)
        pylab.draw()
    #
    elif (event.key == 'a'):
        print "##############################################################"
        print "Please click a point to get the position."
        from matplotlib.widgets import Cursor
        cursor = Cursor(event.inaxes, useblit=False, color='red', linewidth=1)
        point = pylab.ginput(n=1, show_clicks=False, timeout=0)
        print "point = ", point
        event.inaxes.plot(point[0][0], point[0][1],  '+r', lw=1.0)
        pylab.draw()
Esempio n. 24
0
def main(argv):
	# filename = image file
	filename = os.path.realpath(argv[1])
	print filename
	c=mpimg.imread(filename)
	fig=plt.imshow(c)
	plt.draw()

	# the next values should be input for the specific chart
	# use the new opened sketch to decide what they should be
	minX=float(input('minX: '))
	maxX=float(input('maxX: '))
	minY=float(input('minY: '))
	maxY=float(input('maxY: '))

	data = np.asarray(ginput(n=-5,show_clicks=True, timeout=-5))
	X,Y = data[:,0],data[:,1]
	x = []; y = []
	for a,b in zip(X,Y):
		x.append(a)
		y.append(b)

	# first point: min x
	# second point: max x
	# third point: min y
	# fourth point: max y
	# next points - the graph itself.

	TetaX=np.arctan2((y[1]-y[0]),(x[1]-x[0]))
	CosX=np.cos(TetaX)
	SinX=np.sin(TetaX)
	SinTeta=SinX
	CosTeta=CosX

	xOut = x[0:len(x)]
	yOut = y[0:len(y)]

	for i,(xx,yy) in enumerate(zip(x,y)):
		xOut[i] = xx*CosTeta-yy*SinTeta
		yOut[i] = xx*SinTeta+yy*CosTeta

	xOut0, xOut1 = xOut[0], xOut[1]
	yOut2, yOut3 = yOut[2], yOut[3]

	xo = (xOut-xOut0)/(xOut1-xOut0)*(maxX-minX)+minX
	yo = (yOut-yOut2)/(yOut3-yOut2)*(maxY-minY)+minY

	xOut = xo[4:len(xo)]
	yOut = yo[4:len(yo)]
	g = np.column_stack((xOut,yOut))
	f = open('temp.csv','wb')
	csvWriter = csv.writer(f, delimiter=' ')
	csvWriter.writerows(g)
	f.close()

	print xOut
	print yOut
Esempio n. 25
0
    def addgrain(self,ori=0):
        '''
        add a grain inside the microstructure
        
        :param ori: orienation of the new grain [phi1 phi] (default random value)
        :type ori: array, float
        :return: new_micro, object with the new grain include
        :rtype: aita
        :Exemple: 
            >>> data.addgrain()      
        '''
        
        # select the contour of the grains
        h=self.grains.plot()
        # click on the submit of the new grain
        plt.waitforbuttonpress()
        print('click on the submit of the new grain :')
        x=np.array(pylab.ginput(3))/self.grains.res
        plt.close('all')
        
        # select a subarea contening the triangle
        minx=np.int(np.fix(np.min(x[:,0])))
        maxx=np.int(np.ceil(np.max(x[:,0])))
        miny=np.int(np.fix(np.min(x[:,1])))
        maxy=np.int(np.ceil(np.max(x[:,1])))
        
        # write all point inside this area
        gpoint=[]
        for i in list(range(minx,maxx)):
            for j in list(range(miny,maxy)):
                gpoint.append([i,j])
        
    
        # test if the point is inside the triangle    
        gIn=[]
        for i in list(range(len(gpoint))):
            gIn.append(isInsideTriangle(gpoint[i],x[0,:],x[1,:],x[2,:]))

        gpointIn=np.array(gpoint)[np.array(gIn)]
        
        #transform in xIn and yIn, the coordinate of the map
        xIn=np.shape(self.grains.field)[0]-gpointIn[:,1]
        yIn=gpointIn[:,0]
               
        # add one grains
        self.grains.field[xIn,yIn]=np.nanmax(self.grains.field)+1
        # add the orientation of the grains
        if ori==0:
            self.phi1.field[xIn,yIn]=random.random()*2*math.pi
            self.phi.field[xIn,yIn]=random.random()*math.pi/2
        else:
            self.phi1.field[xIn,yIn]=ori[0]
            self.phi.field[xIn,yIn]=ori[1]
            
        returnphi=self.phi1*mask
Esempio n. 26
0
    def load_pts(self, mode='auto'):
        try:
            self.man_update(np.load(self.fh.make_path('pts.npz', mode=self.fh.BL)))
        except:
            if mode == 'auto':
                self.all_possible_pts = []
                invalid = True
                attempts = 0
                while invalid:
                    if attempts > 500:
                        raise Exception('Pts cannot be found.')
                    img = self.background_image.copy()
                    lp_ksizes = [13,15,17,19,21,23,25] #from 5-15 before
                    lp_ksize = rand.choice(lp_ksizes)
                    sbd_areas = [range(3,20), range(61,140)] #8,26 46,55
                    sbd_area = [rand.choice(sbd_areas[0]), rand.choice(sbd_areas[1])]
                    sbd_circs = [np.arange(0.05,0.35), range(1000,1001)]#0.19,0.35 1000
                    sbd_circ = [rand.choice(sbd_circs[0]), rand.choice(sbd_circs[1])]
                    subtr_rowmeans = rand.choice([True,False])

                    if subtr_rowmeans:
                        img = img-np.mean(img,axis=1)[:,None]
                    img = cv2.Laplacian(img, cv2.CV_32F, ksize=lp_ksize)
                    img += abs(img.min())
                    img = img/img.max() *255
                    img = img.astype(np.uint8)

                    #pl.figure(1);pl.imshow(img,cmap=pl.cm.Greys_r)
                    params = cv2.SimpleBlobDetector_Params()
                    params.filterByArea = True
                    params.filterByCircularity = True
                    params.minArea,params.maxArea = sbd_area
                    params.minCircularity,params.maxCircularity = sbd_circ
                    detector = cv2.SimpleBlobDetector(params)
                    fs = detector.detect(img)
                    pts = np.array([f.pt for f in fs])
                    pts = np.round(pts).astype(np.uint32)
                    x = img.copy()
                    for pt in pts:
                        cv2.circle(x, tuple(pt), 4, (255,255,255), thickness=3)
                    #pl.figure(2);pl.imshow(x);raw_input()
                    self.pts = pts
                    invalid = not self.verify_pts()
                    attempts += 1
            elif mode == 'manual':
                pl.imshow(self.background_image, cmap=pl.cm.Greys_r)
                pl.title('center3->middle6->outer6')
                pts = pl.ginput(n=15, timeout=-1)
                pts = np.round(pts).astype(np.uint32)
                self.pts = np.array(pts)
                pl.close()
                # note that verify is being skipped
                self.c3i,self.m6i,self.o6i = np.arange(0,3),np.arange(3,9),np.arange(9,15)
                self.pts_c = np.mean(self.pts, axis=0)
            self.classify_pts()
Esempio n. 27
0
 def createWireMask(self,data=None):
   if data==None:
     import ixppy
     d = ixppy.dataset('/reg/g/xpp/data/example_data/cspad/liquid_scattering/hdf5/xpp43512-r0004.h5',['cspad'])
     data = d.cspad.rdStepData(0,range(10))
   i = np.mean(data,axis=0)
   ib = self.bin(i)
   tools.imagesc(self.xVec,self.yVec,ib)
   tools.clim_std()
   pl.draw()
   print "Roughly select wire end pairs, press middle mouse button when finished."
   wires = []
   tpos = np.array(pl.ginput(2))
   pointno = 0
   while not tpos==[]:
     tpos = np.array(tpos)
     pl.plot(tpos[:,0],tpos[:,1],'go-')
     for pno in range(2):pl.text(tpos[pno,0],tpos[pno,1],str(pointno),color='r')
     wires.append(tpos)
     pointno += 1
     tpos = pl.ginput(2)
   refwires = []
   for pos in wires:
     refwires.append(self._refinePoints(pos,ib))
   wirewidths = []
   print refwires
   for refwire in refwires:
     trad = self._getOneWire(refwire,i,rmax=1000)
     wirewidths.append(trad)
   
   masked = np.zeros(np.shape(i),dtype=bool)
   ax = self.xpx
   ay = self.ypx
   for refwire,wirewidth in zip(refwires,wirewidths):
     points = refwire
     m = np.diff(points[:,1])/np.diff(points[:,0])
     c = points[0,1] - points[0,0]*m
     m_ = -1/m
     dist_perp = (ay-m*ax-c)/np.sqrt(m**2+1)
     dist_par  = (ay-m_*ax)/np.sqrt(m_**2+1)
     masked[np.abs(dist_perp)<wirewidth] = True
   np.save('cspad_last_pixel_mask.npy',masked)
Esempio n. 28
0
def demo_interactive():
    """
    Interactive label
    """    
    im = np.array(Image.open('./computer_vision/scenery.jpg'))
    pl.imshow(im)
    print('Please click 3 points')
    """Get mouse click input from GUI"""
    x = pl.ginput(3)
    print("You've clicked:",x)
    pl.show()
def add_straight_tunnel(tunnels,tunnel_oris,horiz,this_name,parent_name=None,update_plot=1,**kwargs):
	'''
	specify start and end of straight line.  if parent_name is None, treat as hillside
	if update_plot, draws all tunnels in figure specified (e.g. update_plot == 1; plot in figure 1)
	'''
	print >> sys.stderr, 'click start and end'
	tunnels[this_name] = pylab.ginput(2,0)
	if parent_name is not None:
		tunnel_oris[this_name] = parent_name
	if update_plot:
		plot_tunnels(tunnels,horiz,update_plot)
Esempio n. 30
0
def extract_pop(histo, nbr_pic, width) :
    result = []
    X = ginput(nbr_pic)
    size_hist = size(histo[1])
    Xmin = histo[1][0]
    Xmax = histo[1][-1]
    step = 1.0 * abs(Xmax-Xmin)/size_hist
    for i in range(nbr_pic) :
        center = floor(abs(X[i][0] - Xmin)/step)
        result.append(sum(histo[0][center-width:center+width]))
    return [result, 1.0*array(result) / sum(result)]
Esempio n. 31
0
    #注意 返回的是绝对路径
    return [
        os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')
    ]


import pylab as plb
import PIL.Image as Image
#循环读图
for path in getAllImages(r'C:\Users\wentao99\Desktop\11111'):
    #读图
    img = Image.open(path)
    #显示
    plb.imshow(img)
    #设置裁剪点(4个)
    corner = plb.ginput(4)
    #顺时针取点求解
    left = (corner[0][0] + corner[3][0]) / 2
    top = (corner[1][1] + corner[0][1]) / 2
    reight = (corner[1][0] + corner[2][0]) / 2
    under = (corner[3][1] + corner[2][1]) / 2
    #print left,top,reight,under
    #box = [left,top,reight,under]
    #box中的数必须是 int 否则会报错
    box = [int(left), int(top), int(reight), int(under)]
    #裁剪
    img2 = img.crop(box)
    #显示裁剪后的效果
    #plb.imshow(img2)
    #plb.show()
    #储存为原来路径覆盖原文件
Esempio n. 32
0
def coo_max(files, psfName, manual=True):
    py.close(1)
    py.figure(1, figsize=(10, 10))
    py.subplots_adjust(left=0.1, bottom=0.08, right=0.95, top=0.93)

    firstFramePos = None

    for _file in files:
        fileDir, fileName = os.path.split(_file)
        fileRoot, fileExt = os.path.splitext(fileName)

        # Make a max file
        _max = open(fileDir + fileRoot + '.max', 'w')
        _max.write('35000\n')
        _max.close()

        # Read in the image for display to select a coo star
        img, hdr = pyfits.getdata(_file, header=True)
        imgRescale = img_scale.sqrt(img, scale_min=400, scale_max=5000)

        fig = py.figure(1)
        foo = fig.gca().get_xlabel()
        if foo != '':
            psfName = foo

        print 'Getting from old plot:', psfName
        py.clf()
        py.imshow(imgRescale, aspect='equal', cmap=py.cm.gray)
        py.title('{0} PA={1:.0f}'.format(fileRoot, hdr['PA']))
        fig.gca().set_xlabel('{0}'.format(psfName))
        print 'Plotting: ', psfName
        py.ylabel('Press "p" for new star name.')
        fig.canvas.mpl_connect('key_press_event', key_press)

        starFound = False

        while not starFound:
            psfName = fig.gca().get_xlabel()
            print 'In while: ', psfName

            # Get the user selected PSF stars
            if firstFramePos == None or manual == True:

                pts = py.ginput(1, timeout=0)
                xinit = int(round(pts[0][0]))
                yinit = int(round(pts[0][1]))
            else:
                xinit = firstFramePos[0]
                yinit = firstFramePos[1]

            boxSize = 50

            # Get an initial sub-image
            imgSub, xLo, yLo = get_sub_image(img, boxSize, xinit, yinit)

            # Find the maximum pixel value within this box...
            # assume this is the star and re-center up on it
            maxIdx = np.where(imgSub == imgSub.max())
            xinit = xLo + maxIdx[1][0]
            yinit = yLo + maxIdx[0][0]

            # Get an sub-image centered on brightest pixel
            imgSub, xLo, yLo = get_sub_image(img, boxSize, xinit, yinit)

            yc, xc = scipy.ndimage.center_of_mass(imgSub)
            xc += xLo
            yc += yLo
            print '%s  Centroid:  x=%.2f  y=%.2f' % (fileRoot, xc, yc)

            py.figure(2)
            py.clf()
            py.imshow(imgRescale, aspect='equal', cmap=py.cm.gray)
            py.plot([xc], [yc], 'kx', ms=10)
            py.xlim(xc - 30, xc + 30)
            py.ylim(yc - 30, yc + 30)
            py.figure(1)

            gaussInfo = psf.moments(imgSub, SubSize=5)
            g_height = gaussInfo[0]
            g_muX = gaussInfo[1]
            g_muY = gaussInfo[2]
            g_FWHMX = gaussInfo[3]
            g_FWHMY = gaussInfo[4]
            g_FWHM = gaussInfo[5]
            g_Ellip = gaussInfo[6]
            g_angle = gaussInfo[7]

            hdrout = '{0:5s} {1:5s} {2:5s} {3:5s} {4:5s} '
            hdrout += '{5:5s} {6:4s} {7}\n'
            strout = '{0:5.2f} {1:5.2f} {2:5.2f} {3:5.2f} {4:5.2f} '
            strout += '{5:5.2f} {6:4.2f} {7:.1f}\n'

            _gauss = open(fileDir + fileRoot + '.metrics', 'w')
            _gauss.write(
                hdrout.format('muX', 'muY', 'FWHMX', 'FWHMY', 'FWHM', 'Ellip',
                              'Angle', 'Height'))
            _gauss.write(
                strout.format(g_muX, g_muY, g_FWHMX, g_FWHMY, g_FWHM, g_Ellip,
                              g_angle, g_height))
            _gauss.close()

            # Make a max file
            _coo = open(fileDir + fileRoot + '.coo', 'w')
            _coo.write('{0:.2f}  {1:.2f}  {2}\n'.format(xc, yc, psfName))
            _coo.close()

            if firstFramePos == None:
                firstFramePos = [xc, yc]

            starFound = True

    return
Esempio n. 33
0
    def _process_segment(self, page_image, page, page_xywh, page_id,
                         input_file, n):
        LOG = getLogger('OcrdAnybaseocrBinarizer')
        raw = ocrolib.pil2array(page_image)
        if len(raw.shape) > 2:
            raw = np.mean(raw, 2)
        raw = raw.astype("float64")
        # perform image normalization
        image = raw - amin(raw)
        if amax(image) == amin(image):
            LOG.info("# image is empty: %s" % (page_id))
            return
        image /= amax(image)

        # check whether the image is already effectively binarized
        if self.parameter['gray']:
            extreme = 0
        else:
            extreme = (np.sum(image < 0.05) +
                       np.sum(image > 0.95)) * 1.0 / np.prod(image.shape)
        if extreme > 0.95:
            comment = "no-normalization"
            flat = image
        else:
            comment = ""
            # if not, we need to flatten it by estimating the local whitelevel
            LOG.info("Flattening")
            m = interpolation.zoom(image, self.parameter['zoom'])
            m = filters.percentile_filter(m,
                                          self.parameter['perc'],
                                          size=(self.parameter['range'], 2))
            m = filters.percentile_filter(m,
                                          self.parameter['perc'],
                                          size=(2, self.parameter['range']))
            m = interpolation.zoom(m, 1.0 / self.parameter['zoom'])
            if self.parameter['debug'] > 0:
                clf()
                imshow(m, vmin=0, vmax=1)
                ginput(1, self.parameter['debug'])
            w, h = minimum(array(image.shape), array(m.shape))
            flat = clip(image[:w, :h] - m[:w, :h] + 1, 0, 1)
            if self.parameter['debug'] > 0:
                clf()
                imshow(flat, vmin=0, vmax=1)
                ginput(1, self.parameter['debug'])

        # estimate low and high thresholds
        LOG.info("Estimating Thresholds")
        d0, d1 = flat.shape
        o0, o1 = int(self.parameter['bignore'] * d0), int(
            self.parameter['bignore'] * d1)
        est = flat[o0:d0 - o0, o1:d1 - o1]
        if self.parameter['escale'] > 0:
            # by default, we use only regions that contain
            # significant variance; this makes the percentile
            # based low and high estimates more reliable
            e = self.parameter['escale']
            v = est - filters.gaussian_filter(est, e * 20.0)
            v = filters.gaussian_filter(v**2, e * 20.0)**0.5
            v = (v > 0.3 * amax(v))
            v = morphology.binary_dilation(v, structure=ones((int(e * 50), 1)))
            v = morphology.binary_dilation(v, structure=ones((1, int(e * 50))))
            if self.parameter['debug'] > 0:
                imshow(v)
                ginput(1, self.parameter['debug'])
            est = est[v]
        lo = stats.scoreatpercentile(est.ravel(), self.parameter['lo'])
        hi = stats.scoreatpercentile(est.ravel(), self.parameter['hi'])
        # rescale the image to get the gray scale image
        LOG.info("Rescaling")
        flat -= lo
        flat /= (hi - lo)
        flat = clip(flat, 0, 1)
        if self.parameter['debug'] > 0:
            imshow(flat, vmin=0, vmax=1)
            ginput(1, self.parameter['debug'])
        binarized = 1 * (flat > self.parameter['threshold'])

        # output the normalized grayscale and the thresholded images
        # print_info("%s lo-hi (%.2f %.2f) angle %4.1f %s" % (fname, lo, hi, angle, comment))
        LOG.info("%s lo-hi (%.2f %.2f) %s" % (page_id, lo, hi, comment))
        LOG.info("writing")
        if self.parameter['debug'] > 0 or self.parameter['show']:
            clf()
            gray()
            imshow(binarized)
            ginput(1, max(0.1, self.parameter['debug']))

        page_xywh['features'] += ',binarized'

        bin_array = array(255 * (binarized > ocrolib.midrange(binarized)), 'B')
        bin_image = ocrolib.array2pil(bin_array)

        file_id = make_file_id(input_file, self.output_file_grp)
        file_path = self.workspace.save_image_file(
            bin_image,
            file_id + '-IMG',
            page_id=page_id,
            file_grp=self.output_file_grp)
        page.add_AlternativeImage(
            AlternativeImageType(filename=file_path,
                                 comments=page_xywh['features']))
Esempio n. 34
0
    def process(self):
        for (n, input_file) in enumerate(self.input_files):
            pcgts = page_from_file(self.workspace.download_file(input_file))
            fname = pcgts.get_Page().imageFilename
            img = self.workspace.resolve_image_as_pil(fname)
            param = self.parameter
            base, _ = ocrolib.allsplitext(fname)
            #basefile = ocrolib.allsplitext(os.path.basename(fpath))[0]

            if param['parallel'] < 2:
                print_info("=== %s " % (fname))
            raw = ocrolib.read_image_gray(img.filename)

            flat = raw
            #flat = np.array(binImg)
            # estimate skew angle and rotate
            if param['maxskew'] > 0:
                if param['parallel'] < 2:
                    print_info("estimating skew angle")
                d0, d1 = flat.shape
                o0, o1 = int(param['bignore'] * d0), int(param['bignore'] * d1)
                flat = amax(flat) - flat
                flat -= amin(flat)
                est = flat[o0:d0 - o0, o1:d1 - o1]
                ma = param['maxskew']
                ms = int(2 * param['maxskew'] * param['skewsteps'])
                angle = self.estimate_skew_angle(est,
                                                 linspace(-ma, ma, ms + 1))
                flat = interpolation.rotate(flat,
                                            angle,
                                            mode='constant',
                                            reshape=0)
                flat = amax(flat) - flat
            else:
                angle = 0

            # self.write_angles_to_pageXML(base,angle)
            # estimate low and high thresholds
            if param['parallel'] < 2:
                print_info("estimating thresholds")
            d0, d1 = flat.shape
            o0, o1 = int(param['bignore'] * d0), int(param['bignore'] * d1)
            est = flat[o0:d0 - o0, o1:d1 - o1]
            if param['escale'] > 0:
                # by default, we use only regions that contain
                # significant variance; this makes the percentile
                # based low and high estimates more reliable
                e = param['escale']
                v = est - filters.gaussian_filter(est, e * 20.0)
                v = filters.gaussian_filter(v**2, e * 20.0)**0.5
                v = (v > 0.3 * amax(v))
                v = morphology.binary_dilation(v,
                                               structure=ones(
                                                   (int(e * 50), 1)))
                v = morphology.binary_dilation(v,
                                               structure=ones(
                                                   (1, int(e * 50))))
                if param['debug'] > 0:
                    imshow(v)
                    ginput(1, param['debug'])
                est = est[v]
            lo = stats.scoreatpercentile(est.ravel(), param['lo'])
            hi = stats.scoreatpercentile(est.ravel(), param['hi'])
            # rescale the image to get the gray scale image
            if param['parallel'] < 2:
                print_info("rescaling")
            flat -= lo
            flat /= (hi - lo)
            flat = clip(flat, 0, 1)
            if param['debug'] > 0:
                imshow(flat, vmin=0, vmax=1)
                ginput(1, param['debug'])
            deskewed = 1 * (flat > param['threshold'])

            # output the normalized grayscale and the thresholded images
            print_info("%s lo-hi (%.2f %.2f) angle %4.1f" %
                       (pcgts.get_Page().imageFilename, lo, hi, angle))
            if param['parallel'] < 2:
                print_info("writing")
            ocrolib.write_image_binary(base + ".ds.png", deskewed)

            orientation = TextRegionType(orientation=angle)
            pcgts.get_Page().add_TextRegion(orientation)

            ID = concat_padded(self.output_file_grp, n)
            self.workspace.add_file(ID=ID,
                                    file_grp=self.output_file_grp,
                                    pageId=input_file.pageId,
                                    mimetype="image/png",
                                    url=base + ".ds.png",
                                    local_filename='%s/%s' %
                                    (self.output_file_grp, ID),
                                    content=to_xml(pcgts).encode('utf-8'))
Esempio n. 35
0
    def completeness(self, catalogue, config, saveplot=False, filetype='png',
                     timeout=120):
        '''
                
        :param catalogue:
            Earthquake catalogue as instance of 
            :class: hmtk.seismicity.catalogue.Catalogue
        
        :param dict config:
            Configuration parameters of the algorithm, containing the 
            following information - 
                'magnitude_bin' Size of magnitude bin (non-negative float)
                'time_bin' Size (in dec. years) of the time window 
                           (non-negative float)
                'increment_lock' Boolean to indicate whether to ensure
                           completeness magnitudes always decrease with more
                           recent bins
        :returns: 
            2-column table indicating year of completeness and corresponding 
            magnitude numpy.ndarray
        '''
        if saveplot and not isinstance(saveplot, str):
            raise ValueError('To save the figures enter a filename: ')

        # Get magntitude bins
        magnitude_bins = self._get_magnitudes_from_spacing(
            catalogue.data['magnitude'],
            config['magnitude_bin'])
        dec_time = catalogue.get_decimal_time()
        completeness_table = np.zeros([len(magnitude_bins) - 1, 2],
                                      dtype=float)
        min_year = float(np.min(catalogue.data['year']))
        max_year = float(np.max(catalogue.data['year'])) + 1.0
        has_completeness = np.zeros(len(magnitude_bins) - 1, dtype=bool)
        for iloc in range(0, len(magnitude_bins) - 1):
            lower_mag = magnitude_bins[iloc]
            upper_mag = magnitude_bins[iloc + 1]
            idx = np.logical_and(catalogue.data['magnitude'] >= lower_mag,
                                 catalogue.data['magnitude'] < upper_mag)
            cumvals = np.cumsum(np.ones(np.sum(idx)))
            plt.plot(dec_time[idx], cumvals, '.')
            plt.xlim(min_year, max_year + 5)
            title_string = 'Magnitude %5.2f to %5.2f' % (lower_mag, upper_mag)
            plt.title(title_string)
            pts = pylab.ginput(1, timeout=timeout)[0]
            if pts[0] <= max_year:
                 # Magnitude bin has no completeness!
                has_completeness[iloc] = True
            completeness_table[iloc, 0] = np.floor(pts[0])
            completeness_table[iloc, 1] = magnitude_bins[iloc]
            print completeness_table[iloc, :], has_completeness[iloc]
            if config['increment_lock'] and (iloc > 0) and \
                (completeness_table[iloc, 0] > completeness_table[iloc - 1, 0]):
                    completeness_table[iloc, 0] = \
                        completeness_table[iloc - 1, 0]
            # Add marker line to indicate completeness point
            marker_line = np.array([
                    [0., completeness_table[iloc, 0]],
                    [cumvals[-1], completeness_table[iloc, 0]]])
            plt.plot(marker_line[:, 0], marker_line[:, 1], 'r-')
            if saveplot:
                filename = saveplot + '_' + ('%5.2f' % lower_mag) + ('%5.2f'
                    % upper_mag) + '.' + filetype
                plt.savefig(filename, format=filetype)
            plt.close()
        return completeness_table[has_completeness, :]
Esempio n. 36
0
def multi_point_warp(dest_im):
    source_im = np.array(Image.open('images/opencv.jpg'), dtype=np.uint8)
    plt.figure(1)
    plt.imshow(source_im)
    plt.show()

    print("Click source and destination of warp point")
    p = np.asarray(plt.ginput(n=2, mouse_stop=2), dtype=np.float32)
    print(p)
    if (p.size == 0):
        #cv2.imshow('image',dest_im)
        return dest_im, False

    print(p[0] - p[1])
    plt.plot(p[:, 0], p[:, 1], color="blue")
    plt.plot(p[0][0], p[0][1], marker='x', markersize=3, color="red")
    plt.plot(p[1][0], p[1][1], marker='x', markersize=3, color="red")
    #plt.show()
    start = time.time()

    #Generate pixels coordinates in the destination image
    dest_im = np.zeros(source_im.shape, dtype=np.uint8)
    max_row = source_im.shape[0] - 1
    max_col = source_im.shape[1] - 1
    dest_rows = dest_im.shape[0]
    dest_cols = dest_im.shape[1]

    #Painting outline of source image black, so out of bounds pixels can be painted black
    source_im[0] = 0
    source_im[max_row] = 0
    source_im[:, 0] = 0
    source_im[:, max_col] = 0

    #Generate pixel coordinates in the destination image
    ind = np.arange(dest_rows * dest_cols)
    row_vect = ind // dest_cols
    col_vect = ind % dest_cols
    coords = np.vstack((row_vect, col_vect))

    #Computing pixel weights, pixels close to p[1] will have higher weights
    dist = np.sqrt(
        np.square(p[1][1] - row_vect) + np.square(p[1][0] - col_vect))
    weight = np.exp(-dist /
                    100)  #Constant needs to be tweaked depending on image size

    #Computing pixel weights, pixels close to p[1] will have higher weights
    source_coords = np.zeros(coords.shape, dtype=np.int)
    disp_r = (weight * (p[0][1] - p[1][1])).astype(int)
    disp_c = (weight * (p[0][0] - p[1][0])).astype(int)
    source_coords[0] = coords[0] + disp_r
    source_coords[1] = coords[1] + disp_c

    #Fixing out-of-bounds coordinates
    source_coords[source_coords < 0] = 0
    source_coords[0, source_coords[0] > max_row] = max_row
    source_coords[1, source_coords[1] > max_col] = max_col

    dest_im = source_im[source_coords[0],
                        source_coords[1], :].reshape(dest_rows, dest_cols, 3)

    #    cv2.imshow('image',dest_im)

    elapsed_time = time.time() - start
    print('Elapsed time: {0:.2f} '.format(elapsed_time))

    return dest_im, True
Esempio n. 37
0
def _lss_corr(obs,
              interactive=True,
              maxcr=False,
              figno=20,
              rawxy=None,
              target='target',
              chatter=0):
    '''determine the LSS correction for the readout streak source '''
    import os
    import numpy as np
    try:
        from astropy.io import fits
    except:
        import pyfits as fits
    from pylab import figure,imshow,ginput,axvspan,\
         axhspan,plot,autumn,title,clf
    file = obs['infile']
    ext = obs['extension']
    cols = obs['streak_col_SN_CR_ERR']
    kol = []
    countrates = []
    circle = [
        np.sin(np.arange(0, 2 * np.pi, 0.05)),
        np.cos(np.arange(0, 2 * np.pi, 0.05))
    ]
    for k in cols:
        kol.append(k[1])  # S/N
        countrates.append(k[2])
    kol = np.array(kol)
    if len(kol) == 0:
        print("zero array kol in _lss_corr ???!!!!")
        print("LSS correction cannot be determined.")
        return 1.0, (0, 0), (1100.5, 1100.5)
    k_sn_max = np.where(np.max(kol) == kol)  # maximum s/n column
    print("k S/N max=", k_sn_max[0][0])
    kol = []
    for k in cols:
        kol.append(k[0])  # column number relative to bottom rh corner subimage
    if len(kol) == 0:
        print("LSS correction cannot be determined.")
        return 1.0, (0, 0), (1100.5, 1100.5)
    im = fits.getdata(file, ext=ext)
    hdr = fits.getheader(file, ext=ext)
    #binx = hdr['binx']
    mn = im.mean()
    sig = im.std()
    #   plot
    figure(figno)
    clf()
    autumn()
    imshow(im, vmin=mn - 0.2 * sig, vmax=mn + 2 * sig)
    if rawxy != None:
        rawx, rawy = rawxy
        R = hdr['windowdx'] / 15.
        plot(R * circle[0] + rawx - hdr['windowy0'],
             R * circle[1] + rawy - hdr['windowx0'],
             '-',
             color='m',
             alpha=0.7,
             lw=2)
    title(u"PUT CURSOR on your OBJECT", fontsize=16)
    if not maxcr:
        count = 0
        for k in kol:
            axvspan(k - 6,
                    k + 6,
                    0.01,
                    0.99,
                    facecolor='k',
                    alpha=0.3 - 0.02 * count)
            count += 1
    else:
        k = k_sn_max[0][0]
        axvspan(k - 10, k + 10, 0.01, 0.99, facecolor='k', alpha=0.2)
    happy = False
    skip = False
    count = 0
    while not happy:
        print("put the cursor on the location of your source")
        count += 1
        coord = ginput(timeout=0)
        print("selected:", coord)
        if len(coord[0]) == 2:
            print("window corner:", hdr['windowx0'], hdr['windowy0'])
            xloc = coord[0][0] + hdr['windowx0']
            yloc = coord[0][1] + hdr['windowy0']
            print("on detector (full raw image)  should be :", xloc, yloc)
            #plot(coord[0][0],coord[0][1],'+',markersize=14,color='k',lw=2) #can't see it
            axhspan(coord[0][1] - 6,
                    coord[0][1] + 6,
                    0,
                    1,
                    facecolor='k',
                    alpha=0.3)
            if rawxy != None:
                rawx, rawy = rawxy
                R = hdr['windowdx'] / 15.
                plot(R * circle[0] + rawx - hdr['windowx0'],
                     R * circle[1] + rawy - hdr['windowy0'],
                     '-',
                     color='k',
                     alpha=0.7,
                     lw=1)
                #plot(rawx-hdr['windowx0'],rawy-hdr['windowy0'],'o',markersize=25,color='w',alpha=0.3)
            ans = raw_input("happy (yes,skip,no): ")
            if len(ans) > 0:
                if ans.upper()[0] == 'Y':
                    happy = True
                if ans.upper()[0] == 'S':
                    return 0.0, coord[0], (yloc + 104, xloc + 78)
        else:
            print("no position found")
        if count > 10:
            print("Too many tries: aborting")
            happy = True
    im = ''
    try:
        lss = 1.0
        band = obs['band']
        caldb = os.getenv('CALDB')
        command = "quzcif swift uvota - "+band.upper()+\
           " SKYFLAT "+\
           obs['dateobs'].split('T')[0]+"  "+\
    obs['dateobs'].split('T')[1]+" - > lssfile.1234.tmp"
        print(command)
        os.system(command)
        f = open('lssfile.1234.tmp')
        lssfile = f.readline()
        f.close()
        f = fits.getdata(lssfile.split()[0], ext=int(lssfile.split()[1]))
        lss = f[yloc, xloc]
        print("lss correction = ", lss, "  coords=", coord[0],
              (yloc + 104, xloc + 78))
        return lss, coord[0], (yloc + 104, xloc + 78)
    except:
        print("LSS correction cannot be determined.")
        return 1.0, (0, 0), (1100.5, 1100.5)
Esempio n. 38
0
#below is the repeat.
elif mark1 == 'Intensity':  # if input file have the character'Intensity',call this method.
    dr = read_csv(direct + fn,
                  sep=',',
                  skiprows=2,
                  parse_dates={'datet': [1]},
                  index_col='datet',
                  names=[
                      'NO', 'DataTime', 'Temp', 'Intensity', 'CouplerDetached',
                      'CouplerAttached', 'Stopped', 'EndOfFile'
                  ])
    df = DataFrame(dr['Temp'], index=dr.index)
    fig = plt.figure()
    plt.plot(df.index.to_pydatetime(), df.values)
    print "click on start and stop times to save date"
    [start, end] = pylab.ginput(n=2)
    #plt.close()
    plt.clf()
    FF = chooseSE(start, end)
    saveTemFig(dirout)
    ############generate the yeardays##############
    yd = getyearday(FF)
    #############c to f##################
    FT = []
    for k in range(len(FF.index)):
        f = c2f(FF['Temp'][k])
        FT.append(f)
############output file###################
    PFDATA = {
        'sitecode': Series(Sc, index=FF.index),
        'depth': Series(dep, index=FF.index),
Esempio n. 39
0
def draw_transects(output, settings):
    """
    Draw shore-normal transects interactively on top of the mapped shorelines

    KV WRL 2018       

    Arguments:
    -----------
    output: dict
        contains the extracted shorelines and corresponding metadata
    settings: dict with the following keys
        'inputs': dict
            input parameters (sitename, filepath, polygon, dates, sat_list)
            
    Returns:    
    -----------
    transects: dict
        contains the X and Y coordinates of all the transects drawn.
        Also saves the coordinates as a .geojson as well as a .jpg figure 
        showing the location of the transects.       
    """

    sitename = settings['inputs']['sitename']
    filepath = os.path.join(settings['inputs']['filepath'], sitename)

    # plot the mapped shorelines
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    ax1.axis('equal')
    ax1.set_xlabel('Eastings [m]')
    ax1.set_ylabel('Northings [m]')
    ax1.grid(linestyle=':', color='0.5')
    for i in range(len(output['shorelines'])):
        sl = output['shorelines'][i]
        date = output['dates'][i]
        ax1.plot(sl[:, 0],
                 sl[:, 1],
                 '.',
                 markersize=3,
                 label=date.strftime('%d-%m-%Y'))


#    ax1.legend()
    fig1.set_tight_layout(True)
    mng = plt.get_current_fig_manager()
    mng.window.showMaximized()
    ax1.set_title(
        'Click two points to define each transect (first point is the ' +
        'origin of the transect and is landwards, second point seawards).\n' +
        'When all transects have been defined, click on <ENTER>',
        fontsize=16)

    # initialise transects dict
    transects = dict([])
    counter = 0
    # loop until user breaks it by click <enter>
    while 1:
        # let user click two points
        pts = ginput(n=2, timeout=-1)
        if len(pts) > 0:
            origin = pts[0]
        # if user presses <enter>, no points are selected
        else:
            # save figure as .jpg
            fig1.gca().set_title('Transect locations', fontsize=16)
            fig1.savefig(os.path.join(filepath, 'jpg_files',
                                      sitename + '_transect_locations.jpg'),
                         dpi=200)
            plt.title('Transect coordinates saved as ' + sitename +
                      '_transects.geojson')
            plt.draw()
            # wait 2 seconds for user to visualise the transects that are saved
            ginput(n=1, timeout=2, show_clicks=True)
            plt.close(fig1)
            # break the loop
            break

        # add selectect points to the transect dict
        counter = counter + 1
        transect = np.array([pts[0], pts[1]])

        # alternative of making the transect the origin, orientation and length
        #        temp = np.array(pts[1]) - np.array(origin)
        #        phi = np.arctan2(temp[1], temp[0])
        #        orientation = -(phi*180/np.pi - 90)
        #        length = np.linalg.norm(temp)
        #        transect = create_transect(origin, orientation, length)

        transects[str(counter)] = transect

        # plot the transects on the figure
        ax1.plot(transect[:, 0], transect[:, 1], 'b-', lw=2.5)
        ax1.plot(transect[0, 0], transect[0, 1], 'rx', markersize=10)
        ax1.text(transect[-1, 0],
                 transect[-1, 1],
                 str(counter),
                 size=16,
                 bbox=dict(boxstyle="square", ec='k', fc='w'))
        plt.draw()

    # save transects.geojson
    gdf = SDS_tools.transects_to_gdf(transects)
    # set projection
    gdf.crs = {'init': 'epsg:' + str(settings['output_epsg'])}
    # save as geojson
    gdf.to_file(os.path.join(filepath, sitename + '_transects.geojson'),
                driver='GeoJSON',
                encoding='utf-8')
    # print the location of the files
    print('Transect locations saved in ' + filepath)

    return transects
Esempio n. 40
0
def get_reference_sl(metadata, settings):
    """
    Allows the user to manually digitize a reference shoreline that is used seed
    the shoreline detection algorithm. The reference shoreline helps to detect 
    the outliers, making the shoreline detection more robust.

    KV WRL 2018

    Arguments:
    -----------
    metadata: dict
        contains all the information about the satellite images that were downloaded
    settings: dict with the following keys
        'inputs': dict
            input parameters (sitename, filepath, polygon, dates, sat_list)
        'cloud_thresh': float
            value between 0 and 1 indicating the maximum cloud fraction in 
            the cropped image that is accepted
        'cloud_mask_issue': boolean
            True if there is an issue with the cloud mask and sand pixels
            are erroneously being masked on the images
        'output_epsg': int
            output spatial reference system as EPSG code

    Returns:
    -----------
    reference_shoreline: np.array
        coordinates of the reference shoreline that was manually digitized. 
        This is also saved as a .pkl and .geojson file.

    """

    sitename = settings['inputs']['sitename']
    filepath_data = settings['inputs']['filepath']
    pts_coords = []
    # check if reference shoreline already exists in the corresponding folder
    filepath = os.path.join(filepath_data, sitename)
    filename = sitename + '_reference_shoreline.pkl'
    # if it exist, load it and return it
    if filename in os.listdir(filepath):
        print('Reference shoreline already exists and was loaded')
        with open(
                os.path.join(filepath, sitename + '_reference_shoreline.pkl'),
                'rb') as f:
            refsl = pickle.load(f)
        return refsl

    # otherwise get the user to manually digitise a shoreline on S2, L8 or L5 images (no L7 because of scan line error)
    else:
        # first try to use S2 images (10m res for manually digitizing the reference shoreline)
        if 'S2' in metadata.keys():
            satname = 'S2'
            filepath = SDS_tools.get_filepath(settings['inputs'], satname)
            filenames = metadata[satname]['filenames']
        # if no S2 images, try L8  (15m res in the RGB with pansharpening)
        elif not 'S2' in metadata.keys() and 'L8' in metadata.keys():
            satname = 'L8'
            filepath = SDS_tools.get_filepath(settings['inputs'], satname)
            filenames = metadata[satname]['filenames']
        # if no S2 images and no L8, use L5 images (L7 images have black diagonal bands making it
        # hard to manually digitize a shoreline)
        elif not 'S2' in metadata.keys() and not 'L8' in metadata.keys(
        ) and 'L5' in metadata.keys():
            satname = 'L5'
            filepath = SDS_tools.get_filepath(settings['inputs'], satname)
            filenames = metadata[satname]['filenames']
        else:
            raise Exception(
                'You cannot digitize the shoreline on L7 images (because of gaps in the images), add another L8, S2 or L5 to your dataset.'
            )

        # create figure
        fig, ax = plt.subplots(1, 1, figsize=[18, 9], tight_layout=True)
        mng = plt.get_current_fig_manager()
        mng.window.showMaximized()
        # loop trhough the images
        for i in range(len(filenames)):

            # read image
            fn = SDS_tools.get_filenames(filenames[i], filepath, satname)
            im_ms, georef, cloud_mask, im_extra, im_QA, im_nodata = preprocess_single(
                fn, satname, settings['cloud_mask_issue'])

            # calculate cloud cover
            cloud_cover = np.divide(
                sum(sum(cloud_mask.astype(int))),
                (cloud_mask.shape[0] * cloud_mask.shape[1]))

            # skip image if cloud cover is above threshold
            if cloud_cover > settings['cloud_thresh']:
                continue

            # rescale image intensity for display purposes
            im_RGB = rescale_image_intensity(im_ms[:, :, [2, 1, 0]],
                                             cloud_mask, 99.9)

            # plot the image RGB on a figure
            ax.axis('off')
            ax.imshow(im_RGB)

            # decide if the image if good enough for digitizing the shoreline
            ax.set_title(
                'Press <right arrow> if image is clear enough to digitize the shoreline.\n'
                +
                'If the image is cloudy press <left arrow> to get another image',
                fontsize=14)
            # set a key event to accept/reject the detections (see https://stackoverflow.com/a/15033071)
            # this variable needs to be immuatable so we can access it after the keypress event
            skip_image = False
            key_event = {}

            def press(event):
                # store what key was pressed in the dictionary
                key_event['pressed'] = event.key

            # let the user press a key, right arrow to keep the image, left arrow to skip it
            # to break the loop the user can press 'escape'
            while True:
                btn_keep = plt.text(1.1,
                                    0.9,
                                    'keep ⇨',
                                    size=12,
                                    ha="right",
                                    va="top",
                                    transform=ax.transAxes,
                                    bbox=dict(boxstyle="square",
                                              ec='k',
                                              fc='w'))
                btn_skip = plt.text(-0.1,
                                    0.9,
                                    '⇦ skip',
                                    size=12,
                                    ha="left",
                                    va="top",
                                    transform=ax.transAxes,
                                    bbox=dict(boxstyle="square",
                                              ec='k',
                                              fc='w'))
                btn_esc = plt.text(0.5,
                                   0,
                                   '<esc> to quit',
                                   size=12,
                                   ha="center",
                                   va="top",
                                   transform=ax.transAxes,
                                   bbox=dict(boxstyle="square", ec='k',
                                             fc='w'))
                plt.draw()
                fig.canvas.mpl_connect('key_press_event', press)
                plt.waitforbuttonpress()
                # after button is pressed, remove the buttons
                btn_skip.remove()
                btn_keep.remove()
                btn_esc.remove()
                # keep/skip image according to the pressed key, 'escape' to break the loop
                if key_event.get('pressed') == 'right':
                    skip_image = False
                    break
                elif key_event.get('pressed') == 'left':
                    skip_image = True
                    break
                elif key_event.get('pressed') == 'escape':
                    plt.close()
                    raise StopIteration(
                        'User cancelled checking shoreline detection')
                else:
                    plt.waitforbuttonpress()

            if skip_image:
                ax.clear()
                continue
            else:
                # create two new buttons
                add_button = plt.text(0,
                                      0.9,
                                      'add',
                                      size=16,
                                      ha="left",
                                      va="top",
                                      transform=plt.gca().transAxes,
                                      bbox=dict(boxstyle="square",
                                                ec='k',
                                                fc='w'))
                end_button = plt.text(1,
                                      0.9,
                                      'end',
                                      size=16,
                                      ha="right",
                                      va="top",
                                      transform=plt.gca().transAxes,
                                      bbox=dict(boxstyle="square",
                                                ec='k',
                                                fc='w'))
                # add multiple reference shorelines (until user clicks on <end> button)
                pts_sl = np.expand_dims(np.array([np.nan, np.nan]), axis=0)
                geoms = []
                while 1:
                    add_button.set_visible(False)
                    end_button.set_visible(False)
                    # update title (instructions)
                    ax.set_title(
                        'Click points along the shoreline (enough points to capture the beach curvature).\n'
                        + 'Start at one end of the beach.\n' +
                        'When finished digitizing, click <ENTER>',
                        fontsize=14)
                    plt.draw()

                    # let user click on the shoreline
                    pts = ginput(n=50000, timeout=1e9, show_clicks=True)
                    pts_pix = np.array(pts)
                    # convert pixel coordinates to world coordinates
                    pts_world = SDS_tools.convert_pix2world(
                        pts_pix[:, [1, 0]], georef)

                    # interpolate between points clicked by the user (1m resolution)
                    pts_world_interp = np.expand_dims(np.array(
                        [np.nan, np.nan]),
                                                      axis=0)
                    for k in range(len(pts_world) - 1):
                        pt_dist = np.linalg.norm(pts_world[k, :] -
                                                 pts_world[k + 1, :])
                        xvals = np.arange(0, pt_dist)
                        yvals = np.zeros(len(xvals))
                        pt_coords = np.zeros((len(xvals), 2))
                        pt_coords[:, 0] = xvals
                        pt_coords[:, 1] = yvals
                        phi = 0
                        deltax = pts_world[k + 1, 0] - pts_world[k, 0]
                        deltay = pts_world[k + 1, 1] - pts_world[k, 1]
                        phi = np.pi / 2 - np.math.atan2(deltax, deltay)
                        tf = transform.EuclideanTransform(
                            rotation=phi, translation=pts_world[k, :])
                        pts_world_interp = np.append(pts_world_interp,
                                                     tf(pt_coords),
                                                     axis=0)
                    pts_world_interp = np.delete(pts_world_interp, 0, axis=0)

                    # save as geometry (to create .geojson file later)
                    geoms.append(geometry.LineString(pts_world_interp))

                    # convert to pixel coordinates and plot
                    pts_pix_interp = SDS_tools.convert_world2pix(
                        pts_world_interp, georef)
                    pts_sl = np.append(pts_sl, pts_world_interp, axis=0)
                    ax.plot(pts_pix_interp[:, 0], pts_pix_interp[:, 1], 'r--')
                    ax.plot(pts_pix_interp[0, 0], pts_pix_interp[0, 1], 'ko')
                    ax.plot(pts_pix_interp[-1, 0], pts_pix_interp[-1, 1], 'ko')

                    # update title and buttons
                    add_button.set_visible(True)
                    end_button.set_visible(True)
                    ax.set_title(
                        'click on <add> to digitize another shoreline or on <end> to finish and save the shoreline(s)',
                        fontsize=14)
                    plt.draw()

                    # let the user click again (<add> another shoreline or <end>)
                    pt_input = ginput(n=1, timeout=1e9, show_clicks=False)
                    pt_input = np.array(pt_input)

                    # if user clicks on <end>, save the points and break the loop
                    if pt_input[0][0] > im_ms.shape[1] / 2:
                        add_button.set_visible(False)
                        end_button.set_visible(False)
                        plt.title('Reference shoreline saved as ' + sitename +
                                  '_reference_shoreline.pkl and ' + sitename +
                                  '_reference_shoreline.geojson')
                        plt.draw()
                        ginput(n=1, timeout=3, show_clicks=False)
                        plt.close()
                        break

                pts_sl = np.delete(pts_sl, 0, axis=0)
                # convert world image coordinates to user-defined coordinate system
                image_epsg = metadata[satname]['epsg'][i]
                pts_coords = SDS_tools.convert_epsg(pts_sl, image_epsg,
                                                    settings['output_epsg'])

                # save the reference shoreline as .pkl
                filepath = os.path.join(filepath_data, sitename)
                with open(
                        os.path.join(filepath,
                                     sitename + '_reference_shoreline.pkl'),
                        'wb') as f:
                    pickle.dump(pts_coords, f)

                # also store as .geojson in case user wants to drag-and-drop on GIS for verification
                for k, line in enumerate(geoms):
                    gdf = gpd.GeoDataFrame(geometry=gpd.GeoSeries(line))
                    gdf.index = [k]
                    gdf.loc[k, 'name'] = 'reference shoreline ' + str(k + 1)
                    # store into geodataframe
                    if k == 0:
                        gdf_all = gdf
                    else:
                        gdf_all = gdf_all.append(gdf)
                gdf_all.crs = {'init': 'epsg:' + str(image_epsg)}
                # convert from image_epsg to user-defined coordinate system
                gdf_all = gdf_all.to_crs(
                    {'init': 'epsg:' + str(settings['output_epsg'])})
                # save as geojson
                gdf_all.to_file(os.path.join(
                    filepath, sitename + '_reference_shoreline.geojson'),
                                driver='GeoJSON',
                                encoding='utf-8')

                print('Reference shoreline has been saved in ' + filepath)
                break

    # check if a shoreline was digitised
    if len(pts_coords) == 0:
        raise Exception(
            'No cloud free images are available to digitise the reference shoreline,'
            + 'download more images and try again')

    return pts_coords
Esempio n. 41
0
def forward_mapping():
    img = cv2.imread('images/banner_small.jpg', 1)
    triangle1, triangle2 = triangle(img)

    im1 = np.array(triangle1, dtype=np.uint8)
    plt.figure(3)
    plt.imshow(triangle1)
    plt.show()

    x2 = [0, 0, im1.shape[0] - 1]
    y2 = [0, im1.shape[1] - 1, 0]
    fp2 = np.vstack((x2, y2))

    im1 = np.fliplr(im1)
    im1 = np.flipud(im1)

    im2 = np.array(triangle2, dtype=np.uint8)
    plt.figure(1)
    plt.imshow(triangle2)
    plt.show()

    source_im1 = np.array(Image.open('images/tennis.jpg'), dtype=np.uint8)
    source_im = cv2.cvtColor(source_im1, cv2.COLOR_BGR2RGB)
    plt.figure(2)
    plt.imshow(source_im)
    plt.show()

    max_row = source_im.shape[0] - 1
    max_col = source_im.shape[1] - 1

    x = [0, 0, im2.shape[0] - 1]
    y = [0, im2.shape[1] - 1, 0]
    fp = np.vstack((x, y))

    #print("Click destination points, top-left, top-tight, and bottom-left corners")
    tp = np.asarray(plt.ginput(n=3), dtype=np.float).T
    tp = tp[[1, 0], :]
    print('fp', fp)
    print('tp', tp)

    #print("Click destination points, top-right, bottorm-left, and bottom-right corners")
    tp2 = np.asarray(plt.ginput(n=3), dtype=np.float).T
    tp2 = tp2[[1, 0], :]
    print('fp', fp2)
    print('tp', tp2)

    start = time.time()

    #Using pseudoinverse
    # Generating homogeneous coordinates
    fph = np.vstack((fp, np.ones(fp.shape[1])))
    tph = np.vstack((tp, np.ones(tp.shape[1])))
    H = np.dot(tph, np.linalg.pinv(fph))

    fph2 = np.vstack((fp2, np.ones(fp2.shape[1])))
    tph2 = np.vstack((tp2, np.ones(tp2.shape[1])))
    H2 = np.dot(tph2, np.linalg.pinv(fph2))

    print('wat', (transform(H, fp) + .5).astype(np.int))

    Cs = (transform(H, fp) + .5).astype(np.int)
    Cs[Cs < 0] = 0
    Cs[0, Cs[0] > max_row] = max_row
    Cs[1, Cs[1] > max_col] = max_col

    Cs2 = (transform(H2, fp2) + .5).astype(np.int)
    Cs2[Cs2 < 0] = 0
    Cs2[0, Cs2[0] > max_row] = max_row
    Cs2[1, Cs2[1] > max_col] = max_col

    #Generating pixel coordinate locations
    ind = np.arange(im2.shape[0] * im2.shape[1])
    row_vect = ind // im2.shape[1]
    col_vect = ind % im2.shape[1]
    coords = np.vstack((row_vect, col_vect))

    new_coords = transform(H, coords).astype(np.int)
    new_coords[new_coords < 0] = 255
    new_coords[0, new_coords[0] > max_row] = max_row
    new_coords[1, new_coords[1] > max_col] = max_col
    target_im = source_im

    #    print('---------------------------')
    #    for y in range(im2.shape[0]):
    #        for x in range(im2.shape[1]):
    #            if(np.dot(im2[y,x],im2[y,x]) == 0 ):
    #                np.delete(im2, im2[y,x])
    #    print('---------------------------')
    #
    #    print('---------------------------')
    #    for y in range(im1.shape[0]):
    #        for x in range(im1.shape[1]):
    #            if(np.dot(im1[y,x],im1[y,x]) == 0 ):
    #                np.delete(im1, im1[y,x])
    #    print('---------------------------')

    target_im[new_coords[0], new_coords[1], :] = im2[coords[0], coords[1], :]

    #Generating pixel coordinate locations
    ind2 = np.arange(im1.shape[0] * im1.shape[1])
    row_vect2 = ind2 // im2.shape[1]
    col_vect2 = ind2 % im2.shape[1]
    coords2 = np.vstack((row_vect2, col_vect2))

    new_coords2 = transform(H2, coords2).astype(np.int)
    target_im = source_im
    target_im[new_coords2[0], new_coords2[1], :] = im1[coords2[0],
                                                       coords2[1], :]

    elapsed_time = time.time() - start
    print('Elapsed time: {0:.2f} '.format(elapsed_time))

    cv2.imshow('image', target_im)

    plt.figure(3)
    plt.imshow(target_im)
    plt.show()