def set_data(self, arr): arr = np.asarray(arr) self.src_format, self.dst_format = fmts_from_shape(arr.shape, self._texture_dim) # Float is default type if arr.dtype == np.uint8: arr = np.ascontiguousarray(arr) self.src_type = gl.GL_UNSIGNED_BYTE elif arr.dtype == np.float32: arr = np.ascontiguousarray(arr) self.src_type = gl.GL_FLOAT else: arr = np.astype(np.float32) self.src_type = gl.GL_FLOAT self._arr = arr if self._id: gl.glDeleteTextures(1, gl.byref(self._id)) id = gl.GLuint() gl.glGenTextures(1, gl.byref(id)) self._id = id gl.glPixelStorei (gl.GL_UNPACK_ALIGNMENT, 1) gl.glPixelStorei (gl.GL_PACK_ALIGNMENT, 1) gl.glBindTexture (self.target, self._id) gl.glTexParameterf (self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf (self.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf (self.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameterf (self.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) self._setup_tex() self.update()
def axis_identify_indexes(self, di, axis_n): "return indexes that are aligned with the phase and step of axis.index_domain - limited to whole numbers for now" di = self.to_index_array(di, axis_n) im = self.interp_mode if im == "floor": return np.floor(di).astype(np.int_) elif im == "ceil": return np.ceil(di).astype(np.int_) elif im == "round": return np.round(di).astype(np.int_) elif im == "throw": if ((di % 1) != 0).any(): raise IndexError return np.astype(np.int_) elif im in interpolated.interp_order: selector = (di % 1) == 0 constantset = di[selector] interpset = di[~selector] af = np.floor(interpset) ac = np.ceil(interpset) tmp = [] for j in range(interpolated.interp_order[im]): tmp.append(af - j) tmp.append(ac + j) interpset = np.concatenate(tmp) desired_indexes.set(di) ii = np.union1d(constantset, interpset).astype(np.int_) interpolation_indexes.set(ii) return ii else: raise NotImplementedError
def ideallens(wlength, focal_length, center, fshift, diameter, dx, dy, M, N): """ Create function of a ideal paraxial lens INPUTS : wlength -> wavelength of the optical signal f -> 2-by-1 list contains -> focal length in x and focal length in y center -> 2-by-1 list contains -> central shift of whole lens func. in x and y fshift -> lateral off-axis shift on the focal plane dia -> diameter of lens aperture dx,dy -> sampling intervals in space M,N -> size of simulation window OUTPUTS: lensfunc -> numerical lensfunction defined in space """ x = (np.arange(M) - (M - 1) / 2) * dx y = (np.arange(N) - (N - 1) / 2) * dy x0, y0 = center[0], center[1] xf, yf = fshift[0], fshift[1] Lxy2 = (np.outer( (x - x0)**2, np.ones(N)) + np.outer(np.ones(M), (y - y0)**2)) D = Lxy2 <= (diameter**2) D = np.astype('int') sq = np.outer((x - xf)**2, np.ones(N)) + np.outer(np.ones(M), (y - yf)**2) R = (sq + focal_length**2)**(0.5) lensfunc = np.exp(-1j * 2 * np.pi / wlength * R) * D lensfunc = tf.convert_to_tensor(lensfunc, dtype=tf.complex64) lensfunc = tf.reshape(lensfunc, shape=[1, M * N], name='lens') return lensfunc
def ovrRead(dataset, x=0, y=0, w=None, h=None, ovrindex=None, bstart=1, bcount=None, dtype=None): '''Read an image block from overviews of all spacified bands. This function read a data block from the overview corresponding to *ovrindex* for all *bcount* raster bands starting drom the *bstart*\ th one. Parameters: dataset: GDAL dataset object the GDAL dataset to read from x, y: int origin of the box to read in overview coordinates w, h: int size of the box to read in overview coordinates ovrindex: int index of the overview to read from. If the overview index is `None` data are retrieved directly from the raster band instead of overviews. bstart: int raster band start index (default 1). bcount: int or None raster band count (defaut all starting from *bstart*) Returns: data: ndarray the array of data read with shape (h, w, bcount) ''' # @TODO: check RasterColorInterpretation if bcount is None: bcount = dataset.RasterCount assert bstart > 0 assert bstart - 1 + bcount <= dataset.RasterCount #data = np.zeros((h, w, dataset.RasterCount), np.ubyte) channels = [] for bandindex in range(bstart, bstart + bcount): band = dataset.GetRasterBand(bandindex) if ovrindex is not None: band = band.GetOverview(ovrindex) channels.append(band.ReadAsArray(x, y, w, h)) data = np.dstack(channels) if dtype and dtype != data.dtype: return np.astype(data) else: return data
def df_over_f_THEIA(self, images, take_lowest_percentile=5): """ Calculates the delta F over F for a image series :param images: the images to process :param take_lowest_percentile: the lowest percentile of brightness to take as F0 :return: processed images """ F0 = np.percentile(images, take_lowest_percentile, 0) return (np.astype(images, np.float32) - F0) / F0
def testJaxRoundTrip(self, shape, dtype): rng = jtu.rand_default() np = rng(shape, dtype) x = jnp.array(np) dlpack = jax.dlpack.to_dlpack(x) y = jax.dlpack.from_dlpack(dlpack) self.assertAllClose(np.astype(x.dtype), y, check_dtypes=True) self.assertRaisesRegex(RuntimeError, "DLPack tensor may be consumed at most once", lambda: jax.dlpack.from_dlpack(dlpack))
def testJaxRoundTrip(self, shape, dtype, take_ownership): rng = jtu.rand_default(self.rng()) np = rng(shape, dtype) x = jnp.array(np) dlpack = jax.dlpack.to_dlpack(x, take_ownership=take_ownership) self.assertEqual(take_ownership, x.device_buffer.is_deleted()) y = jax.dlpack.from_dlpack(dlpack) self.assertAllClose(np.astype(x.dtype), y) self.assertRaisesRegex(RuntimeError, "DLPack tensor may be consumed at most once", lambda: jax.dlpack.from_dlpack(dlpack))
def testJaxRoundTrip(self, shape, dtype, take_ownership): if jax.lib.version < (0, 1, 57) and not take_ownership: raise unittest.SkipTest("Requires jaxlib >= 0.1.57") rng = jtu.rand_default(self.rng()) np = rng(shape, dtype) x = jnp.array(np) dlpack = jax.dlpack.to_dlpack(x, take_ownership=take_ownership) self.assertEqual(take_ownership, x.device_buffer.is_deleted()) y = jax.dlpack.from_dlpack(dlpack) self.assertAllClose(np.astype(x.dtype), y) self.assertRaisesRegex(RuntimeError, "DLPack tensor may be consumed at most once", lambda: jax.dlpack.from_dlpack(dlpack))
def forward(self, bottom, top): from scipy import ndimage try: seg = predict_seg(bottom) seg = np.uint8(seg * 255) rgb = bottom[0].data depth = bottom[1] cont = np.gradient(seg) cont = cont[0] * cont[0] + cont[1] * cont[1] cont = np.astype(float) cont = 1 / (1 + cont) cont = np.transpose(cont, (2, 0, 1)) # top[0].data[...] = rgb + cont.reshape(1,*cont.shape) act = cont[:, :, 0] # rgb = bottom[0].data top[0].data[...] = rgb epsilon = np.ones(depth) epsilon = np.astype(float) var = np.log10(np.var(np.dot(depth, act))) print var epsilon *= np.log2(var) except Exception as e: print e
def draw_image(img,windowsize=None,zoomaxes=None): # get axes if not input if zoomaxes is None: zoomaxes = [0,img.shape[1]-1,0,img.shape[0]-1] # check to make sure valid if (int(zoomaxes[3]) < int(zoomaxes[2])) or (int(zoomaxes[1]) < int(zoomaxes[0])): raise ValueError('Invalid zoom axes input') # crop image scale_img = img.copy() scale_img = scale_img[int(zoomaxes[2]):int(zoomaxes[3]+1),int(zoomaxes[0]):int(zoomaxes[1]+1)] # resize image so that it fits in the window if windowsize is not None: scale_x = float(windowsize[1])/float(scale_img.shape[1]) scale_y = float(windowsize[0])/float(scale_img.shape[0]) if scale_x < scale_y: size_x = windowsize[1] size_y = scale_img.shape[0]*scale_x resize = scale_x else: size_y = windowsize[0] size_x = scale_img.shape[1]*scale_y resize = scale_y scale_img = imresize(scale_img,(int(size_y),int(size_x))) # create an rgb image out of img if scale_img.ndim == 3: if not (scale_img.dtype == 'uint8'): scale_img = scale_img.astype('uint8') elif scale_img.dtype == 'uint8': scale_img = to_rgb8('MONO8',scale_img) elif scale_img.dtype == 'double': # scale to between 0 and 255 scale_img = num.astype(img_normalize(scale_img)*255.,'uint8') scale_img = to_rgb8('MONO8',scale_img) #print 'image shape:' #print scale_img.shape #print 'resize: %f'%resize # create a bitmap out of image h,w,three = scale_img.shape img_size = [h,w] image = wx.EmptyImage(w,h) image.SetData( scale_img.tostring() ) bmp = wx.BitmapFromImage(image) return (bmp,resize,img_size)
def testJaxRoundTrip(self, shape, dtype, take_ownership, gpu): rng = jtu.rand_default(self.rng()) np = rng(shape, dtype) if gpu and jax.default_backend() == "cpu": raise unittest.SkipTest("Skipping GPU test case on CPU") device = jax.devices("gpu" if gpu else "cpu")[0] x = jax.device_put(np, device) dlpack = jax.dlpack.to_dlpack(x, take_ownership=take_ownership) self.assertEqual(take_ownership, x.device_buffer.is_deleted()) y = jax.dlpack.from_dlpack(dlpack) self.assertEqual(y.device(), device) self.assertAllClose(np.astype(x.dtype), y) self.assertRaisesRegex(RuntimeError, "DLPack tensor may be consumed at most once", lambda: jax.dlpack.from_dlpack(dlpack))
def body_per_bins(i, total_conv, w_spatial, co_matrix, x, input_index, vec_input_index, strides): """ the function is a body of the loop that run on the size of a co-occurrence matrix :param i: iteration number :param total_conv: final variable that contains the result :param w_spatial: the spatial filter :param co_matrix: the co-occurrence matrix :param x: the input of the layer :param input_index: the quantized input for the bins of co-occurrence matrix :param vec_input_index: reshaped input_index :param strides: optionally can be implemented stride :return: """ # shape of input data x_shape = np.shape(x) w_shape = np.shape(w_spatial) # fx, fy, fin, fout = w_spatial.get_shape().as_list() # take only the line with specific bin bin_row = co_matrix[i, :] cof_matrix_bin = np.reshape(np.take(bin_row, vec_input_index), x_shape) # temp_mask = np.tile(temp_mask, [1, 1, 1, fout])# num_output_channels]) temp_input = np.multiply(x, cof_matrix_bin) temp_input = np.expand_dims(temp_input, axis=4) w_3d = np.reshape(w_spatial, [w_shape[0], w_shape[1], w_shape[2], 1, 1]) strid = strides.get_shape().as_list() temp_mask = np.astype(np.equal(input_index, i), float) temp_mask = np.expand_dims(temp_mask, axis=4) "Following lines don't change temp_mask value" # filter_ones = np.ones([1, 1, 1, 1, 1]) # temp_mask = np.nn.conv3d(temp_mask, filter_ones, strides=[1, strid[0], strid[0], 1, 1], padding="SAME") //TODO: Downsampaling instead od 3D convolution temp_result = fftconvolve(temp_input, w_3d, mode="SAME") # temp_result = np.reduce_sum(temp_result, axis=4) temp_result = np.multiply(temp_result[:, :, :, :, 0], temp_mask[:, :, :, :, 0]) total_conv = total_conv + temp_result return i + 1, total_conv, w_spatial, co_matrix, x, input_index, vec_input_index, strides
def non_max_suppression(confidences, bboxes, overlapThresh=0.6): # if there are no boxes, return an empty list if len(bboxes) == 0: return [] # if the bounding boxes integers, convert them to floats -- # this is important since we'll be doing a bunch of divisions if bboxes.dtype.kind == "i": bboxes = np.astype(bboxes, np.float32) # initialize the list of picked indexes pick = [] idxs = [(c, i) for i, c in enumerate(confidences)] idxs = sorted(idxs, key=lambda x: x[0]) _, idxs = zip(*idxs) idxs = list(idxs) # keep looping while some indexes still remain in the indexes # list while len(idxs) > 0: # grab the last index in the indexes list and add the # index value to the list of picked indexes last = len(idxs) - 1 i = idxs[last] del idxs[last] pick.append(i) mark_deleted = [] for k, j in enumerate(idxs): overlap = get_iou(bboxes[i], bboxes[j]) if overlap >= overlapThresh or bbox_in_bbox( bboxes[i], bboxes[j], 1 - (1 - overlapThresh)**2): mark_deleted.append(k) for k in reversed(mark_deleted): del idxs[k] # return only the bounding boxes that were picked using the # integer data type return pick
def __call__(self, sample): a, b, c = np.astype(self.scale * np.pi * np.abs(np.random.normal(size=3))), dtype='float') R = RandomRotation.get_matrix(a, b, c) res = np.dot(R, sample) return res
def draw_annotated_image(img,pointlists=None,linelists=None,circlelists=None, windowsize=None,zoomaxes=None, pointcolors=None,linecolors=None,circlecolors=None, pointsizes=None,linewidth=None,circlewidths=None): #print 'in draw_annotated_image' # get axes if not input if zoomaxes is None: zoomaxes = [0,img.shape[1]-1,0,img.shape[0]-1] # check to make sure valid if (int(zoomaxes[3]) < int(zoomaxes[2])) or (int(zoomaxes[1]) < int(zoomaxes[0])): raise ValueError('Invalid zoom axes input') # crop image scale_img = img.copy() scale_img = scale_img[int(zoomaxes[2]):int(zoomaxes[3]+1),int(zoomaxes[0]):int(zoomaxes[1]+1)] xoffset = -zoomaxes[0] yoffset = -zoomaxes[2] #print 'zoomaxes = ' + str(zoomaxes) # resize image so that it fits in the window if windowsize is not None: scale_x = float(windowsize[1])/float(scale_img.shape[1]) scale_y = float(windowsize[0])/float(scale_img.shape[0]) if scale_x < scale_y: size_x = windowsize[1] size_y = scale_img.shape[0]*scale_x resize = scale_x else: size_y = windowsize[0] size_x = scale_img.shape[1]*scale_y resize = scale_y scale_img = imresize(scale_img,(int(size_y),int(size_x))) #print 'current size of scale_img = ' + str(scale_img.shape) # create an rgb image out of img if scale_img.ndim == 3: if not (scale_img.dtype == 'uint8'): scale_img = scale_img.astype('uint8') elif scale_img.dtype == 'uint8': scale_img = to_rgb8('MONO8',scale_img) elif scale_img.dtype == 'double': # scale to between 0 and 255 scale_img = num.astype(img_normalize(scale_img)*255.,'uint8') scale_img = to_rgb8('MONO8',scale_img) #print 'image shape after converting to rgb:' #print scale_img.shape #print 'resize: %f'%resize # create a bitmap out of image h,w,three = scale_img.shape img_size = [h,w] image = wx.EmptyImage(w,h) #print 'created empty image of size (%d,%d)'%(w,h) image.SetData( scale_img.tostring() ) #print 'set the data' bmp = wx.BitmapFromImage(image) #print 'created bmp' # draw into bmp drawDC = wx.MemoryDC() drawDC.SelectObject( bmp ) # draw into bmp # set default point color drawDC.SetPen(wx.Pen('GREEN')) drawDC.SetBrush(wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT)) # by default set point radius to 8 point_radius=8 #print 'starting to draw stuff' if pointlists is not None: pointcolor = 'GREEN' for i,points in enumerate(pointlists): # set color if (pointcolors is not None) and (len(pointcolors) > i): pointcolor = wx.Colour(pointcolors[i][0],pointcolors[i][1],pointcolors[i][2]) if (pointsizes is not None) and (len(pointsizes) > i): point_radius = pointsizes[i] drawDC.SetPen(wx.Pen(colour=pointcolor,width=point_radius)) # set radius for j,pt in enumerate(points): # draw a circle x = int((xoffset+pt[0])*resize) y = int((yoffset+pt[1])*resize) if (x >= 0) and (x < img_size[1]) and \ (y >= 0) and (y < img_size[0]): drawDC.DrawCircle(x,y,point_radius) #print 'finished drawing points' if linelists is not None: # set default line color linecolor = 'GREEN' # set default line width if linewidth is None: linewidth = 1 for i,lines in enumerate(linelists): #print i # create a list of wxPoints points = [] for j,pt in enumerate(lines): x = int((xoffset+pt[0])*resize) y = int((yoffset+pt[1])*resize) newpoint = wx.Point(x,y) if (j < 1) or not (newpoint == lastpoint): points.append(newpoint) lastpoint = newpoint if len(points) == 0: continue if len(points) == 1: points.append(newpoint) # set color if (linecolors is not None) and (len(linecolors) > i): linecolor = wx.Colour(linecolors[i][0],linecolors[i][1], linecolors[i][2]) drawDC.SetPen(wx.Pen(colour=linecolor,width=linewidth)) #print 'drawing line with color' #print linecolor #print 'width' #print linewidth #print 'points' #print points # draw the lines drawDC.DrawLines(points) #print 'finished drawing lines' if circlelists is not None: circlecolor = 'GREEN' for i,circles in enumerate(circlelists): # set color if (circlecolors is not None) and (len(circlecolors) > i): circlecolor = wx.Colour(circlecolors[i][0],circlecolors[i][1],circlecolors[i][2]) if (circlewidths is not None) and (len(circlewidths) > i): circlewidth = circlewidths[i] drawDC.SetPen(wx.Pen(colour=circlecolor,width=circlewidth)) # set radius if (circlewidths is not None) and (len(circlewidths) > i): circlewidth = circlewidths[i] for j,circle in enumerate(circles): # draw a circle x = int((xoffset+circle[0])*resize) y = int((yoffset+circle[1])*resize) r = int(circle[2]*resize) if (x >= 0) and (x < img_size[1]) and \ (y >= 0) and (y < img_size[0]): drawDC.DrawCircle(x,y,r) #print 'finished drawing circles' #print 'leaving draw_annotated_image' return (bmp,resize,img_size)
marker = marker.astype("Int64") genotyp2 = Input.iloc[marker] genotyp2 = genotyp2.transpose() genotyp2 = genotyp2.astype("Int64") #Dieser Datentyp wird für GBLUP und Netzwerke benötigt genotyp2 = Input.iloc[marker] return genotyp2 #Skript FT10 = pd.read_csv("../BachelorThesis/Data/imputed_full/genos_f/FT10.csv", index_col=0) pheno = pd.read_csv("../BachelorThesis/Data/imputed_full/phenos_f/FT10.csv", index_col=0) index = pheno.iloc[:,0] FT10.index = index lat = pd.read_csv("../BachelorThesis/Data/Simulation/Latitude.csv", index_col=0) accessions_all = lat.iloc[:,0] filter = np.isin(accessions_all,index) possible_acc = accessions_all[filter] x = np.arange(0, 100) x = x.astype("str") for k in x: sample = np.random.choice(possible_acc,300) #Auswahl von Accessions sample = np.unique(sample) sample = sample[:200] sample = np.asarray(sample) sample = np.astype("int") genos = FT10.loc[sample] genotyp = set_geno(Input=genos, Input_filter=genos, number=20) #Auswahl der Marker del genotyp.index.name genotyp = genotyp.astype("Int64") name = "S" + k + ".csv" path = "../BachelorThesis/Data/Simulation/genos_f/" + name genotyp.to_csv(path)
import numpy as n from pylab import figure, show import matplotlib.cm as cm import matplotlib.colors as colors fig = figure() ax = fig.add_subplot(111) Ntotal = 1000 N, bins, patches = ax.hist(n.random.random((Ntotal,2)), 20) #I'll color code by height, but you could use any scalar # we need to normalize the data to 0..1 for the full # range of the colormap fracs = [n.astype(float)/n.max() for n in N] norm = [colors.normalize(frac.min(), frac.max()) for frac in fracs ] for i, (thisfrac, thispatch) in enumerate( zip(fracs, patches) ): color = cm.jet(norm[i](thisfrac)) for p in thispatch: #thispatch.set_facecolor(color) p.set_facecolor(color) show()
def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True): """Smooth images by applying a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr. Parameters ========== arr: numpy.ndarray 4D array, with image number as last dimension. 3D arrays are also accepted. affine: numpy.ndarray (4, 4) matrix, giving affine transformation for image. (3, 3) matrices are also accepted (only these coefficients are used). fwhm: scalar or numpy.ndarray Smoothing strength, as a full-width at half maximum, in millimeters. If a scalar is given, width is identical on all three directions. A numpy.ndarray must have 3 elements, giving the FWHM along each axis. If fwhm is None, no filtering is performed (useful when just removal of non-finite values is needed) ensure_finite: bool if True, replace every non-finite values (like NaNs) by zero before filtering. copy: bool if True, input array is not modified. False by default: the filtering is performed in-place. Returns ======= filtered_arr: numpy.ndarray arr, filtered. Notes ===== This function is most efficient with arr in C order. """ if arr.dtype.kind == 'i': if arr.dtype == np.int64: arr = np.astype(arr, np.float64) else: # We don't need crazy precision arr = np.astype(arr, np.float32) if copy: arr = arr.copy() # Keep only the scale part. affine = affine[:3, :3] if ensure_finite: # SPM tends to put NaNs in the data outside the brain arr[np.logical_not(np.isfinite(arr))] = 0 if fwhm is not None: # Convert from a FWHM to a sigma: # Do not use /=, fwhm may be a numpy scalar fwhm = fwhm / np.sqrt(8 * np.log(2)) vox_size = np.sqrt(np.sum(affine ** 2, axis=0)) sigma = fwhm / vox_size for n, s in enumerate(sigma): ndimage.gaussian_filter1d(arr, s, output=arr, axis=n) return arr
def draw_annotated_image(img,pointlists=None,linelists=None,circlelists=None, windowsize=None,zoomaxes=None, pointcolors=None,linecolors=None,circlecolors=None, pointsizes=None,linewidths=None,circlewidths=None): #print 'in draw_annotated_image' # get axes if not input if zoomaxes is None: zoomaxes = [0,img.shape[1]-1,0,img.shape[0]-1] # check to make sure valid if (int(zoomaxes[3]) < int(zoomaxes[2])) or (int(zoomaxes[1]) < int(zoomaxes[0])): raise ValueError('Invalid zoom axes input') # crop image scale_img = img.copy() scale_img = scale_img[int(zoomaxes[2]):int(zoomaxes[3]+1),int(zoomaxes[0]):int(zoomaxes[1]+1)] xoffset = -zoomaxes[0] yoffset = -zoomaxes[2] #print 'zoomaxes = ' + str(zoomaxes) # resize image so that it fits in the window if windowsize is not None: scale_x = float(windowsize[1])/float(scale_img.shape[1]) scale_y = float(windowsize[0])/float(scale_img.shape[0]) if scale_x < scale_y: size_x = windowsize[1] size_y = scale_img.shape[0]*scale_x resize = scale_x else: size_y = windowsize[0] size_x = scale_img.shape[1]*scale_y resize = scale_y scale_img = imresize(scale_img,(int(size_y),int(size_x))) #print 'current size of scale_img = ' + str(scale_img.shape) # create an rgb image out of img if scale_img.ndim == 3: if not (scale_img.dtype == 'uint8'): scale_img = scale_img.astype('uint8') elif scale_img.dtype == 'uint8': scale_img = to_rgb8('MONO8',scale_img) elif scale_img.dtype == 'double': # scale to between 0 and 255 scale_img = num.astype(img_normalize(scale_img)*255.,'uint8') scale_img = to_rgb8('MONO8',scale_img) #print 'image shape after converting to rgb:' #print scale_img.shape #print 'resize: %f'%resize # create a bitmap out of image h,w,three = scale_img.shape img_size = [h,w] image = wx.EmptyImage(w,h) #print 'created empty image of size (%d,%d)'%(w,h) image.SetData( scale_img.tostring() ) #print 'set the data' bmp = wx.BitmapFromImage(image) #print 'created bmp' # draw into bmp drawDC = wx.MemoryDC() drawDC.SelectObject( bmp ) # draw into bmp # set default point color drawDC.SetPen(wx.Pen('GREEN')) drawDC.SetBrush(wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT)) # by default set point radius to 8 point_radius=8 #print 'starting to draw stuff' if pointlists is not None: pointcolor = 'GREEN' for i,points in enumerate(pointlists): # set color if (pointcolors is not None) and (len(pointcolors) > i): pointcolor = wx.Colour(pointcolors[i][0],pointcolors[i][1],pointcolors[i][2]) if (pointsizes is not None) and (len(pointsizes) > i): point_radius = pointsizes[i] drawDC.SetPen(wx.Pen(colour=pointcolor,width=point_radius)) # set radius for j,pt in enumerate(points): # draw a circle x = int((xoffset+pt[0])*resize) y = int((yoffset+pt[1])*resize) if (x >= 0) and (x < img_size[1]) and \ (y >= 0) and (y < img_size[0]): drawDC.DrawCircle(x,y,point_radius) #print 'finished drawing points' if linelists is not None: # set default line color linecolor = 'GREEN' # set default line width linewidth = 1 for i,lines in enumerate(linelists): #print i # create a list of wxPoints points = [] for j,pt in enumerate(lines): x = int((xoffset+pt[0])*resize) y = int((yoffset+pt[1])*resize) newpoint = wx.Point(x,y) if (j < 1) or not (newpoint == lastpoint): points.append(newpoint) lastpoint = newpoint if len(points) == 0: continue if len(points) == 1: points.append(newpoint) # set color if (linecolors is not None) and (len(linecolors) > i): linecolor = wx.Colour(linecolors[i][0],linecolors[i][1], linecolors[i][2]) # set width if (linewidths is not None) and (len(linewidths) > i): linewidth = linewidths[i] drawDC.SetPen(wx.Pen(colour=linecolor,width=linewidth)) #print 'drawing line with color' #print linecolor #print 'width' #print linewidth #print 'points' #print points # draw the lines drawDC.DrawLines(points) #print 'finished drawing lines' if circlelists is not None: circlecolor = 'GREEN' for i,circles in enumerate(circlelists): # set color if (circlecolors is not None) and (len(circlecolors) > i): circlecolor = wx.Colour(circlecolors[i][0],circlecolors[i][1],circlecolors[i][2]) if (circlewidths is not None) and (len(circlewidths) > i): circlewidth = circlewidths[i] drawDC.SetPen(wx.Pen(colour=circlecolor,width=circlewidth)) # set radius if (circlewidths is not None) and (len(circlewidths) > i): circlewidth = circlewidths[i] for j,circle in enumerate(circles): # draw a circle x = int((xoffset+circle[0])*resize) y = int((yoffset+circle[1])*resize) r = int(circle[2]*resize) if (x >= 0) and (x < img_size[1]) and \ (y >= 0) and (y < img_size[0]): drawDC.DrawCircle(x,y,r) #print 'finished drawing circles' #print 'leaving draw_annotated_image' return (bmp,resize,img_size)
def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True): """Smooth images by applying a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr. Parameters ========== arr: numpy.ndarray 4D array, with image number as last dimension. 3D arrays are also accepted. affine: numpy.ndarray (4, 4) matrix, giving affine transformation for image. (3, 3) matrices are also accepted (only these coefficients are used). fwhm: scalar or numpy.ndarray Smoothing strength, as a full-width at half maximum, in millimeters. If a scalar is given, width is identical on all three directions. A numpy.ndarray must have 3 elements, giving the FWHM along each axis. If fwhm is None, no filtering is performed (useful when just removal of non-finite values is needed) ensure_finite: bool if True, replace every non-finite values (like NaNs) by zero before filtering. copy: bool if True, input array is not modified. False by default: the filtering is performed in-place. Returns ======= filtered_arr: numpy.ndarray arr, filtered. Notes ===== This function is most efficient with arr in C order. """ if arr.dtype.kind == 'i': if arr.dtype == np.int64: arr = np.astype(arr, np.float64) else: # We don't need crazy precision arr = np.astype(arr, np.float32) if copy: arr = arr.copy() # Keep only the scale part. affine = affine[:3, :3] if ensure_finite: # SPM tends to put NaNs in the data outside the brain arr[np.logical_not(np.isfinite(arr))] = 0 if fwhm is not None: # Convert from a FWHM to a sigma: # Do not use /=, fwhm may be a numpy scalar fwhm = fwhm / np.sqrt(8 * np.log(2)) vox_size = np.sqrt(np.sum(affine**2, axis=0)) sigma = fwhm / vox_size for n, s in enumerate(sigma): ndimage.gaussian_filter1d(arr, s, output=arr, axis=n) return arr