def fig2(plt,days,values): fig, axes = plt.subplots(4,1,figsize=(8,4)) plt.subplots_adjust(hspace=0.5) ## plot each index for i in range(4): ## display MM/DD/YYYY axes[i].xaxis.set_major_formatter(dates.DateFormatter('%m/%d/%y')) ## label each new day/month/year axes[i].xaxis.set_major_locator(dates.MonthLocator()) ## break up the i-th time series into quartiles horizon(axes[i],days[i],values[i],4) axes[i].grid() axes[i].set(title=filenames[i],ylabel='Value',xlabel='Time') pass plt.gcf().autofmt_xdate() ## display and save #plt.show() plt.savefig('stockMarket-Horizon.png') pass
def create_isopach(hor1, hor2, extent='intersection'): """Create new horizon with the difference between hor1 and hor2.""" if isinstance(extent, basestring): if extent.lower() == 'union': extent = bbox_union(hor1.grid_extents, hor2.grid_extents) elif extent.lower() == 'intersection': extent = bbox_intersection(hor1.grid_extents, hor2.grid_extents) if extent is None: raise ValueError('Horizons do not overlap!') else: raise ValueError('Invalid extent type specified') xmin, xmax, ymin, ymax = extent x, y = np.mgrid[xmin:xmax+1, ymin:ymax+1] hor1.grid_extents = extent hor2.grid_extents = extent grid = hor1.grid - hor2.grid mask = ~grid.mask * np.ones_like(grid, dtype=np.bool) x, y, z, mask = x.ravel(), y.ravel(), grid.ravel(), mask.ravel() iso = horizon.horizon(x=x[mask], y=y[mask], z=z[mask]) iso._grid = grid return iso
print("Skipping %d frames..." % counter) else: continue print("Frame %d" % counter) method = cv2.INTER_AREA frame_scale = cv2.resize(frame, (0, 0), fx=scale, fy=scale, interpolation=method) cv2.imshow('scaled orig', frame_scale) frame_undist = cv2.undistort(frame_scale, K, np.array(dist)) # test horizon detection lines = horizon.horizon(frame_undist) if not lines is None: #best_line = horizon.track_best(lines) best_line = lines[0] roll, pitch = horizon.get_camera_attitude(best_line, IK, cu, cv) if last_roll is None or last_pitch is None: roll_rate = 0 pitch_rate = 0 else: roll_rate = (roll - last_roll) * fps * d2r pitch_rate = (pitch - last_pitch) * fps * d2r last_roll = roll last_pitch = pitch horizon.draw(frame_undist, best_line, IK, cu, cv) row = { 'frame': counter,
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion in voxels lower: (default, upper) lower window interval around horizion in voxels offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, overlap between horizion and volume) sub-region to use instead of full extent. Must be a 4-tuple of (xmin, xmax, ymin, ymax) masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the # upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create # the objects if type(hor) == type('String'): hor = horizon.horizon(hor) if type(vol) == type('String'): vol = volume.volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # Find the overlap between the horizon and volume vol_extents = [vol.xmin, vol.xmax, vol.ymin, vol.ymax] hor_extents = [hor.xmin, hor.xmax, hor.ymin, hor.ymax] extents = bbox_intersection(hor_extents, vol_extents) # Raise ValueError if horizon and volume do not intersect if extents is None: raise ValueError('Input horizon and volume do not intersect!') # Find the overlap between the (optional) subregion current extent if region is not None: extents = bbox_intersection(extents, region) if extents is None: raise ValueError('Specified region does not overlap with'\ ' horizon and volume') elif len(extents) != 4: raise ValueError('"extents" must be a 4-tuple of'\ ' (xmin, xmax, ymin, ymax)') xmin, xmax, ymin, ymax = extents # Convert extents to volume indicies and select subset of the volume xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin data = vol.data[xstart:xstop, ystart:ystop, :] # Convert extents to horizion grid indicies and select # subset of the horizion xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when # iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory # efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower... for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases # where the window goes outside the data bounds (find region of # overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i, j, window_top : window_bottom] \ = data[i, j, data_top : data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so # return 2D array instead subVolume = subVolume.squeeze() return subVolume
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion in voxels lower: (default, upper) lower window interval around horizion in voxels offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, overlap between horizion and volume) sub-region to use instead of full extent. Must be a 4-tuple of (xmin, xmax, ymin, ymax) masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the # upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create # the objects if type(hor) == type('String'): hor = horizon.horizon(hor) if type(vol) == type('String'): vol = volume.volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # Find the overlap between the horizon and volume vol_extents = [vol.xmin, vol.xmax, vol.ymin, vol.ymax] hor_extents = [hor.xmin, hor.xmax, hor.ymin, hor.ymax] extents = bbox_intersection(hor_extents, vol_extents) # Raise ValueError if horizon and volume do not intersect if extents is None: raise ValueError('Input horizon and volume do not intersect!') # Find the overlap between the (optional) subregion current extent if region is not None: extents = bbox_intersection(extents, region) if extents is None: raise ValueError('Specified region does not overlap with'\ ' horizon and volume') elif len(extents) != 4: raise ValueError('"extents" must be a 4-tuple of'\ ' (xmin, xmax, ymin, ymax)') xmin, xmax, ymin, ymax = extents # Convert extents to volume indicies and select subset of the volume i, j = vol.model2index([xmin, xmax], [ymin, ymax]) data = vol.data[i[0]:i[1], j[0]:j[1], :] # Convert extents to horizion grid indicies and select # subset of the horizion hxmin, hxmax, hymin, hymax = hor.grid_extents xstart, ystart = xmin - hxmin, ymin - hymin xstop, ystop = xmax - hxmin, ymax - hymin depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when # iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory # efficient, and almost as fast mask = depth.mask.copy() # Need to preserve the mask for later if not mask.shape: mask = np.zeros(depth.shape, dtype=np.bool) depth = depth.filled() # Iterating through masked arrays is much slower. for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset if z < 0: mask[i,j] = True continue top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases # where the window goes outside the data bounds (find region of # overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i, j, window_top : window_bottom] \ = data[i, j, data_top : data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so # return 2D array instead subVolume = subVolume.squeeze() return subVolume
# Save the diamond square image Image.fromarray( (ds).astype('uint8')).convert('RGB').save('0-diamond-square.png') # Binarize the diamond square margin = 10 nb_pixels = ds.shape[0] * ds.shape[1] mean = numpy.mean(ds) binary = numpy.array((ds < mean - margin) + (ds > mean + margin), dtype=numpy.int) # take care of side borders ds_h = binary.shape[0] ds_w = binary.shape[1] horizon_roughness = 0.65 b = horizon(binary.shape[0], horizon_roughness, ds_h // 20) for i in range(binary.shape[0]): binary[i, 0:b[i]] = 0 b = horizon(binary.shape[0], horizon_roughness, ds_h // 20) for i in range(binary.shape[0]): binary[i, (binary.shape[1] - b[-i]):binary.shape[1]] = 0 b = horizon(binary.shape[1], horizon_roughness, ds_w // 20) for i in range(binary.shape[1]): binary[0:b[i], i] = 0 b = horizon(binary.shape[1], horizon_roughness, ds_w // 20) for i in range(binary.shape[1]): binary[(binary.shape[0] - b[-i]):binary.shape[0], i] = 0 # Save it for fun Image.fromarray( (255 * binary).astype('uint8')).convert('RGB').save('1-binary.png')
else: continue #print("Frame %d" % counter) method = cv2.INTER_AREA frame_scale = cv2.resize(frame, (0, 0), fx=scale, fy=scale, interpolation=method) cv2.imshow('scaled orig', frame_scale) frame_undist = cv2.undistort(frame_scale, K, np.array(dist)) # test horizon detection if args.no_otsu: lines = horizon.horizon(frame_undist, False) else: lines = horizon.horizon(frame_undist) if not lines is None: #best_line = horizon.track_best(lines) best_line = lines[0] roll, pitch = horizon.get_camera_attitude(best_line, IK, cu, cv) if last_roll is None or last_pitch is None: roll_rate = 0 pitch_rate = 0 else: roll_rate = (roll - last_roll) * fps * d2r pitch_rate = (pitch - last_pitch) * fps * d2r last_roll = roll last_pitch = pitch horizon.draw(frame_undist, best_line, IK, cu, cv)