def save_tuple(tupla, folder, PATH_out, rotation=False, reflection=False, jitter = False, rotation_vect = [30, 60, 90], n_jitter = 10, max_g = 1.1,min_g = 0.9,max_z = 0.05): # check if there's no K's cont = 0 for ID, image, ground_truth in tupla: if np.sum(ground_truth)!=0: name = ID+'.png' fullfile_im = os.path.join(PATH_out,folder,folder+'2018',name) fullfile_gt = os.path.join(PATH_out,folder,'annotations',name) misc.imsave(fullfile_im,image) misc.imsave(fullfile_gt,ground_truth) if rotation: for idx, angle in enumerate(rotation_vect): name = ID+'r'+str(idx)+'.png' fullfile_im = os.path.join(PATH_out,folder,folder+'2018',name) fullfile_gt = os.path.join(PATH_out,folder,'annotations',name) misc.imsave(fullfile_im,ndimage.interpolation.rotate(image, angle = angle, reshape = False)) misc.imsave(fullfile_gt,ndimage.interpolation.rotate(ground_truth, angle = angle, reshape = False, mode = 'nearest')) if reflection: tupla = [(image.shape,True,False),(image.shape,False,True),(image.shape,True,True)] for idx,t in enumerate(tupla): name = ID + 'x'+str(idx)+'.png' fullfile_im = os.path.join(PATH_out,folder,folder+'2018',name) fullfile_gt = os.path.join(PATH_out,folder,'annotations',name) misc.imsave(fullfile_im,ndimage.geometric_transform(image,reflex, extra_arguments = t)) misc.imsave(fullfile_gt,ndimage.geometric_transform(ground_truth,reflex, extra_arguments = t)) if jitter: im_list, gr_list = jitter_fun(image,ground_truth,n_jitter,max_g,min_g,max_z) for idx, im in enumerate(im_list): name = ID + 'j'+str(idx)+'.png' fullfile_im = os.path.join(PATH_out,folder,folder+'2018',name) fullfile_gt = os.path.join(PATH_out,folder,'annotations',name) misc.imsave(fullfile_im,im) misc.imsave(fullfile_gt,gr_list[idx]) cont += 1 return cont
def _scale_im(self,im,scale): def _scale_1024(out,scale): x = (out[1]-512.)/scale + 512. y = (out[0]-512.)/scale + 512. return y,x def _scale_1600(out,scale): x = (out[1]-800.)/scale + 800. y = (out[0]-800.)/scale + 800. return y,x def _scale_512(out, scale): x = (out[1]-256.)/scale + 256. y = (out[0]-256.)/scale + 256. return y,x im = np.asarray(im,dtype=np.float32) bp,im = nt.reset_nans(im) if (self.central): im = nd.geometric_transform(im,_scale_512,extra_arguments=(scale,)) bp = nd.geometric_transform(bp,_scale_512,extra_arguments=(scale,)) else: im = nd.geometric_transform(im,_scale_1024,extra_arguments=(scale,)) bp = nd.geometric_transform(bp,_scale_1024,extra_arguments=(scale,)) im = nt.restore_nans(im,bp) return im
def polar_warp(im, sz, r): #""" Warp an image to a square polar version. """ h, w = im.shape[:2] def polar_2_rect(xy): #""" Convert polar coordinates to coordinates in # the original image for geometric_transform. """ x, y = float(xy[1]), float(xy[0]) theta = 0.5 * arctan2(x - sz / 2, y - sz / 2) R = sqrt((x - sz / 2) * (x - sz / 2) + (y - sz / 2) * (y - sz / 2)) - r return (2 * h * R / (sz - 2 * r), w / 2 + theta * w / pi + pi / 2) # if color image, warp each channel, otherwise there's just one if len(im.shape) == 3: warped = zeros((sz, sz, 3)) for i in range(3): warped[:, :, i] = geometric_transform(im[:, :, i], polar_2_rect, output_shape=(sz, sz), mode='nearest') else: warped = geometric_transform(im, polar_2_rect, output_shape=(sz, sz), mode='nearest') return warped
def panorama(H,fromim,toim,padding=2400,delta=2400): """ Create horizontal panorama by blending two images using a homography H (preferably estimated using RANSAC). The result is an image with the same height as toim. 'padding' specifies number of fill pixels and 'delta' additional translation. """ # check if images are grayscale or color is_color = len(fromim.shape) == 3 # homography transformation for geometric_transform() def transf(p): p2 = dot(H,[p[0],p[1],1]) return (p2[0]/p2[2],p2[1]/p2[2]) if H[1,2]<0: # fromim is to the right print 'warp - right' # transform fromim if is_color: # pad the destination image with zeros to the right toim_t = hstack((toim,zeros((toim.shape[0],padding,3)))) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # pad the destination image with zeros to the right toim_t = hstack((toim,zeros((toim.shape[0],padding)))) fromim_t = ndimage.geometric_transform(fromim,transf, (toim.shape[0],toim.shape[1]+padding)) else: print 'warp - left' # add translation to compensate for padding to the left H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]]) H = dot(H,H_delta) # transform fromim if is_color: # pad the destination image with zeros to the left toim_t = hstack((zeros((toim.shape[0],padding,3)),toim)) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # pad the destination image with zeros to the left toim_t = hstack((zeros((toim.shape[0],padding)),toim)) fromim_t = ndimage.geometric_transform(fromim, transf,(toim.shape[0],toim.shape[1]+padding)) # blend and return (put fromim above toim) if is_color: # all non black pixels alpha = ((fromim_t[:,:,0] * fromim_t[:,:,1] * fromim_t[:,:,2] ) > 0) for col in range(3): toim_t[:,:,col] = fromim_t[:,:,col]*alpha + toim_t[:,:,col]*(1-alpha) else: alpha = (fromim_t > 0) toim_t = fromim_t*alpha + toim_t*(1-alpha) return toim_t
def panorama(H,fromim,toim,padding=2400,delta=2400): """ Create horizontal panorama by blending two images using a homography H (preferably estimated using RANSAC). The result is an image with the same height as toim. 'padding' specifies number of fill pixels and 'delta' additional translation. """ # check if images are grayscale or color is_color = len(fromim.shape) == 3 # homography transformation for geometric_transform() def transf(p): p2 = dot(H,[p[0],p[1],1]) return (p2[0]/p2[2],p2[1]/p2[2]) if H[1,2]<0: # fromim is to the right print('warp - right') # transform fromim if is_color: # pad the destination image with zeros to the right toim_t = hstack((toim,zeros((toim.shape[0],padding,3)))) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # pad the destination image with zeros to the right toim_t = hstack((toim,zeros((toim.shape[0],padding)))) fromim_t = ndimage.geometric_transform(fromim,transf, (toim.shape[0],toim.shape[1]+padding)) else: print('warp - left') # add translation to compensate for padding to the left H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]]) H = dot(H,H_delta) # transform fromim if is_color: # pad the destination image with zeros to the left toim_t = hstack((zeros((toim.shape[0],padding,3)),toim)) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # pad the destination image with zeros to the left toim_t = hstack((zeros((toim.shape[0],padding)),toim)) fromim_t = ndimage.geometric_transform(fromim, transf,(toim.shape[0],toim.shape[1]+padding)) # blend and return (put fromim above toim) if is_color: # all non black pixels alpha = ((fromim_t[:,:,0] * fromim_t[:,:,1] * fromim_t[:,:,2] ) > 0) for col in range(3): toim_t[:,:,col] = fromim_t[:,:,col]*alpha + toim_t[:,:,col]*(1-alpha) else: alpha = (fromim_t > 0) toim_t = fromim_t*alpha + toim_t*(1-alpha) return toim_t
def panorama(H,fromim,toim,padding=2400,delta=2400): """ ホモグラフィー行列H(RANSACで推定するのが望ましい)を用いて、 2つの画像を合成して水平方向のパノラマを作成する。 出力画像はtoimと同じ高さ。'padding'は横に追加する画素数。 'delta'は水平移動量 """ # 画像がグレースケールかカラーかを調べる is_color = len(fromim.shape) == 3 # geometric_transform()に必要な同次変換 def transf(p): p2 = dot(H,[p[0],p[1],1]) return (p2[0]/p2[2],p2[1]/p2[2]) if H[1,2]<0: # fromim が右側なら print 'warp - right' # fromimを変形 if is_color: # 出力画像の右側に0の領域を追加する toim_t = hstack((toim,zeros((toim.shape[0],padding,3)))) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # 出力画像の右側に0の領域を追加する toim_t = hstack((toim,zeros((toim.shape[0],padding)))) fromim_t = ndimage.geometric_transform(fromim,transf, (toim.shape[0],toim.shape[1]+padding)) else: print 'warp - left' # 左側に領域を追加するために水平移動する H_delta = array([[1,0,0],[0,1,-delta],[0,0,1]]) H = dot(H,H_delta) # fromimを変形 if is_color: # 出力画像の左側に0の領域を追加する toim_t = hstack((zeros((toim.shape[0],padding,3)),toim)) fromim_t = zeros((toim.shape[0],toim.shape[1]+padding,toim.shape[2])) for col in range(3): fromim_t[:,:,col] = ndimage.geometric_transform(fromim[:,:,col], transf,(toim.shape[0],toim.shape[1]+padding)) else: # 出力画像の左側に0の領域を追加する toim_t = hstack((zeros((toim.shape[0],padding)),toim)) fromim_t = ndimage.geometric_transform(fromim,transf, (toim.shape[0],toim.shape[1]+padding)) # 画像を合成して返す(toimにfromimを重ねる) if is_color: # 非0の全ピクセル alpha = ((fromim_t[:,:,0] + fromim_t[:,:,1] + fromim_t[:,:,2] ) > 0) for col in range(3): toim_t[:,:,col] = fromim_t[:,:,col]*alpha + toim_t[:,:,col]*(1-alpha) else: alpha = (fromim_t > 0) toim_t = fromim_t*alpha + toim_t*(1-alpha) return toim_t
def createIntegratedPsf (self): """Compute a PSF for each wavelength, and add them up.""" (wavelengths, weights) = self.filter for i in range (len (wavelengths)): wavelength = wavelengths[i] weight = weights[i] self.convertToOpd (wavelength) # creates self.opd opd = self.embedOpd() zf = numpy.fft.fft2 (opd) del opd # Compute the amplitude squared. # (psf is not really the point spread function yet) psf = np.conjugate (zf) # psf will now be the point spread function, but still complex np.multiply (psf, zf, psf) del zf # normalize the PSF, and convert to single precision psf = psf.real / psf.size psf = psf.astype (np.float32) self.center (psf) # This describes the image scale if no resampling is done. cdelt_before_resampling = (wavelength * MICRONStoMETERS) / \ (self.D * self.oversample) * RADIANStoDEGREES if self.pixel_size is None: # we won't resample the output image self.cdelt = cdelt_before_resampling # Extract a subset. if self.output_size < self.npix: o_npix = self.output_size n0 = (self.npix - o_npix) // 2 self.integrated_psf += \ (psf[n0:n0+o_npix,n0:n0+o_npix] * weight) else: self.integrated_psf += (psf * weight) else: # we'll resample to this image scale self.cdelt = self.pixel_size / self.oversample * ARCSECtoDEGREES # These three parameters are only used by mapPsf and for # normalizing the weight after resampling. self.rescale = self.cdelt / cdelt_before_resampling self.input_center = (self.npix + 1) // 2 self.output_center = (self.output_size + 1) // 2 sub_psf = np.zeros ((self.output_size,self.output_size), dtype=np.float32) # Do the resampling, writing the output to sub_psf. ndimage.geometric_transform (psf, self.mapPsf, output_shape=(self.output_size,self.output_size), output=sub_psf, prefilter=True) weight = weight * self.rescale**2 self.integrated_psf += (sub_psf * weight) del sub_psf if self.verbose: print("PSF for wavelength %g has been computed" % wavelength)
def panorama(H, fromim, toim, padding=2400, delta=2400, alpha=1): """使用RANSAC估计得到的单应性矩阵H,协调两幅图像,创建水平全景图 结果为一幅和toim具有相同高度的图像,padding制定填充像素的数目,delta制定额外的平移量""" # 检查是否是彩色图像 is_color = len(fromim.shape) == 3 if H[1, 2] < 0: # fromim在右边 if is_color: # 在目标图像的右边填充0 toim_t = numpy.hstack( (toim, numpy.zeros((toim.shape[0], padding, 3)))) formim_t = numpy.zeros( (toim.shape[0], toim.shape[1] + padding, toim.shape[2])) for col in range(3): formim_t[:, :, col] = ndimage.geometric_transform( fromim[:, :, col], transf(toim.shape[0], toim.shape[1] + padding)) else: # 在目标的右边填充0 toim_t = numpy.hstack((toim, numpy.zeros( (toim.shape[0], padding)))) formim_t = ndimage.geometric_transform( fromim, transf(toim.shape[0], toim.shape[1] + padding)) else: # fromim在左边 # 为了补偿填充效果,在左边加入平移量 H_delta = numpy.array([[1, 0, 0], [0, 1, -delta], [0, 0, 1]]) H = numpy.dot(H, H_delta) if is_color: # 在目标图像的左边填充0 toim_t = numpy.hstack((numpy.zeros( (toim.shape[0], padding, 3)), toim)) formim_t = numpy.zeros( (toim.shape[0], toim.shape[1] + padding, toim.shape[2])) for col in range(3): formim_t[:, :, col] = ndimage.geometric_transform( fromim[:, :, col], transf(toim.shape[0], toim.shape[1] + padding)) else: # 在目标的左边填充0 toim_t = numpy.hstack((numpy.zeros( (toim.shape[0], padding)), toim)) formim_t = ndimage.geometric_transform( fromim, transf(toim.shape[0], toim.shape[1] + padding)) # 协调后返回(将formim放置在toim上) if is_color: alpha = ((formim_t[:, :, 0] * fromim[:, :, 1] * fromim[:, :, 2]) > 0) for col in range(3): toim_t[:, :, col] = formim_t[:, :, col] * alpha + toim_t[:, :col] * (1 - alpha) else: alpha = (formim_t > 0) toim_t = formim_t * alpha + toim_t * (1 - alpha) return toim_t
def check(j): func = TRANSFORM_FUNCTIONS[j] im = np.arange(12).reshape(4, 3).astype(np.float64) shift = 0.5 res = ndimage.geometric_transform(im, func(shift)) std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,)) assert_allclose(res, std, err_msg="#{} failed".format(j))
def test_geometric_transform(): def transform(output_coordinates, shift): return output_coordinates[0] - shift, output_coordinates[1] - shift im = np.arange(12).reshape(4, 3).astype(np.float64) shift = 0.5 for mod in MODULES: res = ndimage.geometric_transform(im, _ctest.transform(shift)) std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,)) assert_allclose(res, std, err_msg="{} failed".format(mod.__name__))
def test_geometric_transform22(self, order): data = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], numpy.float64) def mapping1(x): return (x[0] / 2, x[1] / 2) def mapping2(x): return (x[0] * 2, x[1] * 2) out = ndimage.geometric_transform(data, mapping1, (6, 8), order=order) out = ndimage.geometric_transform(out, mapping2, (3, 4), order=order) assert_array_almost_equal(out, data)
def horizontal_panorama(H, fromim, toim, padding=2400, delta=2400): ''' Create horizontal panorama by blending two images using a homography H (preferably estimated using RANSAC). The result is an image with the same height as toim. padding specifies number of fill pixels and delta additional translation. ''' is_color = len(fromim.shape) == 3 size = (toim.shape[0], toim.shape[1] + padding) def transf(p): p2 = dot(H, [p[0], p[1], 1]) return [p2[0] / p2[2], p2[1] / p2[2]] if H[1, 2] < 0: # fromim is to the right if is_color: toim_t = hstack((toim, zeros((toim.shape[0], padding, 3)))) fromim_t = zeros((toim.shape[0], toim.shape[1] + padding, toim.shape[2])) for col in range(3): fromim_t[:, :, col] = ndimage.geometric_transform(fromim[:, :, col], transf, # output_shape=size ) else: toim_t = hstack((toim, zeros((toim.shape[0], padding)))) fromim_t = ndimage.geometric_transform(fromim, transf, # output_shape=size ) else: if is_color: toim_t = hstack((zeros((toim.shape[0], padding, 3)), toim)) fromim_t = zeros((toim.shape[0], toim.shape[1] + padding, toim.shape[2])) for col in range(3): fromim_t[:, :, col] = ndimage.geometric_transform(fromim[:, :, col], transf, # output_shape=size ) else: toim_t = hstack((zeros((toim.shape[0], padding)), toim)) fromim_t = ndimage.geometric_transform(fromim, transf, # output_shape=size ) if is_color: alpha = ((fromim_t[:, :, 0] * fromim_t[:, :, 1] * fromim_t[:, :, 2]) > 0) for col in range(3): toim_t[:, :, col] = fromim_t[:, :, col] * alpha + toim_t[:, :, col] * (1 - alpha) else: alpha = (fromim_t > 0) toim_t = fromim_t * alpha + toim_t * (1 - alpha) return toim_t
def ast_register(infile,outfile,inext=0,outext=0,incoord=[]): inpoint = pyfits.open(infile) outpoint = pyfits.open(outfile) if not inext: for i in range(len(inpoint)): try: test = inpoint[i].header['CRVAL1'] inext = i break except: pass if not outext: for i in range(len(outpoint)): try: test = outpoint[i].header['CRVAL1'] outext = i break except: pass print ('Read in=%s[%d], out=%s[%d]' % (infile,inext,outfile,outext)) indata = inpoint[inext].data while indata.ndim>2: indata=indata[0] inheader = inpoint[inext].header outdata = outpoint[outext].data while outdata.ndim>2: outdata=outdata[0] outheader = outpoint[outext].header pickle.dump (inheader, open('hin.npy','wb')) pickle.dump (outheader, open('hout.npy','wb')) os.system('rm inpos.npy') ast_getmap('hin.npy','hout.npy',np.asarray(outdata.shape),incoord=incoord) register = ndimage.geometric_transform (indata,ast_map,output_shape=outdata.shape) return register
def frget(d, h, i, uvw, times, maxoff, fsiz, dofilt): tdec = h['crval'][h['ctype'].index('DEC')] nc = h['naxis'][h['ctype'].index('FREQ')] * h['naxis'][h['ctype'].index( 'IF')] chwid = h['cdelt'][h['ctype'].index('FREQ')] fring = abs(fft.fftshift(fft.fft2(d))) fring = fring_filter(fring) if dofilt else fring alpha, beta, gamma, delta = frd2xy(uvw[i], tdec, chwid, nc, times[-1] - times[0]) xoff,yoff = np.meshgrid(np.arange(fring.shape[1],dtype='float'),\ np.arange(fring.shape[0],dtype='float')) xoff -= 0.5 * fring.shape[1] yoff -= 0.5 * fring.shape[0] det = 1.0 / (alpha * delta - beta * gamma) xp, yp = det * (delta * xoff - beta * yoff), det * (-gamma * xoff + alpha * yoff) maxoff = np.deg2rad(maxoff) if maxoff == 0.0: maxoff = max(xp.max(), -xp.min(), yp.max(), -yp.min()) mat = np.asarray( np.meshgrid(np.arange(float(fsiz)), np.arange(float(fsiz)))) mat = maxoff * (mat - 0.5 * fsiz) / (0.5 * fsiz) px, py = alpha * mat[0] + beta * mat[1], gamma * mat[0] + delta * mat[1] fmap = ndimage.geometric_transform(fring,shift_func,\ output_shape=(fsiz,fsiz),extra_arguments=(px,py,fring.shape)).T fmap = np.fliplr(fmap) # HA -> RA, flip about centre return fmap, np.rad2deg(maxoff)
def shift_elements(original, deformations): x_def, y_def = deformations def shift_func(image): return (image[0] - x_def[image], image[1] - y_def[image]) return ndimage.geometric_transform(original, shift_func)
def gtransform(self,im): """ #xn = a + b*x + c*y #yn = d + e*x + f*y #print 'out wOld' #def gfunc(out): # xref=out[1] # yref=out[0] # # # this is the cannonical solution (iraf.geomap) # x = 990.5897 - 0.9985259*xref - 0.0178984*yref # y = 37.82109 - 0.0181331*xref + 0.9991414*yref # # newer iraf.geomap # #x = 990.2734 - 0.9979063*xref - 0.0186165*yref # #y = 37.68222 - 0.01741749*xref + 0.9985356*yref # # return y,x """ def gfunc(out): xref = out[1] yref = out[0] x = 990.5897-0.9985259*xref - 0.0178984*yref y = 37.82109 -0.0181331*xref + 0.9991414*yref return y,x return nd.geometric_transform(im, gfunc)
def panorama(H, fromim, toim, padding=2400, delta=2400, alpha=1): """使用RANSAC估计得到的单应性矩阵H,协调两幅图像,创建水平全景图 结果为一幅和toim具有相同高度的图像,padding制定填充像素的数目,delta制定额外的平移量""" # 检查是否是彩色图像 is_color = len(fromim.shape) == 3 if H[1, 2] < 0: # fromim在右边 if is_color: # 在目标图像的右边填充0 toim_t = numpy.hstack((toim, numpy.zeros((toim.shape[0], padding, 3)))) formim_t = numpy.zeros((toim.shape[0], toim.shape[1]+padding, toim.shape[2])) for col in range(3): formim_t[:, :, col] = ndimage.geometric_transform(fromim[:, :, col], transf(toim.shape[0], toim.shape[1]+padding)) else: # 在目标的右边填充0 toim_t = numpy.hstack((toim, numpy.zeros((toim.shape[0], padding)))) formim_t = ndimage.geometric_transform(fromim, transf(toim.shape[0], toim.shape[1]+padding)) else: # fromim在左边 # 为了补偿填充效果,在左边加入平移量 H_delta = numpy.array([[1, 0, 0], [0, 1, -delta], [0, 0, 1]]) H = numpy.dot(H, H_delta) if is_color: # 在目标图像的左边填充0 toim_t = numpy.hstack((numpy.zeros((toim.shape[0], padding, 3)), toim)) formim_t = numpy.zeros((toim.shape[0], toim.shape[1] + padding, toim.shape[2])) for col in range(3): formim_t[:, :, col] = ndimage.geometric_transform(fromim[:, :, col], transf(toim.shape[0], toim.shape[1] + padding)) else: # 在目标的左边填充0 toim_t = numpy.hstack((numpy.zeros((toim.shape[0], padding)), toim)) formim_t = ndimage.geometric_transform(fromim, transf(toim.shape[0], toim.shape[1] + padding)) # 协调后返回(将formim放置在toim上) if is_color: alpha = ((formim_t[:, :, 0] * fromim[:, :, 1] * fromim[:, :, 2]) > 0) for col in range(3): toim_t[:, :, col] = formim_t[:, :, col] * alpha + toim_t[:, : col] * (1 - alpha) else: alpha = (formim_t > 0) toim_t = formim_t * alpha + toim_t * (1 - alpha) return toim_t
def test_geometric_transform21(self, order): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] / 2, x[1] / 2) out = ndimage.geometric_transform(data, mapping, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data)
def test_geometric_transform18(self, order): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] * 2, x[1] * 2) out = ndimage.geometric_transform(data, mapping, (1, 2), order=order) assert_array_almost_equal(out, [[1, 3]])
def test_geometric_transform13(self, order): data = numpy.ones([2], numpy.float64) def mapping(x): return (x[0] // 2,) out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 1, 1, 1])
def test_geometric_transform14(self, order): data = [1, 5, 2, 6, 3, 7, 4, 4] def mapping(x): return (2 * x[0],) out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 2, 3, 4])
def test_geometric_transform15(self, order): data = [1, 2, 3, 4] def mapping(x): return (x[0] / 2,) out = ndimage.geometric_transform(data, mapping, [8], order=order) assert_array_almost_equal(out[::2], [1, 2, 3, 4])
def test_boundaries2(self, mode, expected_value): def shift(x): return (x[0] - 0.9,) data = numpy.array([1, 2, 3, 4]) assert_array_equal( expected_value, ndimage.geometric_transform(data, shift, cval=-1, mode=mode, output_shape=(4,)))
def test_geometric_transform04(self, order): data = numpy.array([4, 1, 3, 2]) def mapping(x): return (x[0] - 1,) out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [0, 4, 1, 3])
def test_geometric_transform23(self, order): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (1, x[0] * 2) out = ndimage.geometric_transform(data, mapping, (2, ), order=order) out = out.astype(numpy.int32) assert_array_almost_equal(out, [5, 7])
def test_geometric_transform01(self, order): data = numpy.array([1]) def mapping(x): return x out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [1])
def test_geometric_transform_with_string_output(self): data = numpy.array([1]) def mapping(x): return x out = ndimage.geometric_transform(data, mapping, output='f') assert_(out.dtype is numpy.dtype('f')) assert_array_almost_equal(out, [1])
def shift2D_workaround(A, shiftTuple): """ A : array to be shifted """ return nd.geometric_transform(A, lambda coords: ((coords[0] - shiftTuple[0]) % A.shape[0], (coords[1] - shiftTuple[1]) % A.shape[1]), mode='wrap')
def get_ray(X_real, x, y, output_shape, delta): return geometric_transform( X_real, get_transform(x, y, output_shape[0], delta=delta), order = 3, mode = 'constant', cval= 2, prefilter = True, output_shape = output_shape )
def resample(self, moving, order=3, mode='constant', cval=0.0, prefilter=True, output_dtype=None): """ Resample the moving image in reference space. Parameters ---------- moving : `spatialimage` The image object containing the data to be resampled in reference space order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional Determines how the input image is extended when the resamplings overflows a border. Default is 'constant'. cval : float, optional Constant value for ``mode='constant'``. Default is 0.0. prefilter: bool, optional Determines if the moving image's data array is prefiltered with a spline filter before interpolation. The default is ``True``, which will create a temporary *float64* array of filtered values if *order > 1*. If setting this to ``False``, the output will be slightly blurred if *order > 1*, unless the input is prefiltered, i.e. it is the result of calling the spline filter on the original input. Returns ------- moved_image : `spatialimage` The moving imaged after resampling to reference space. """ moving_data = np.asanyarray(moving.dataobj) if output_dtype is None: output_dtype = moving_data.dtype moved = ndi.geometric_transform( moving_data, mapping=self.map_voxel, output_shape=self.reference.shape, output=output_dtype, order=order, mode=mode, cval=cval, prefilter=prefilter, extra_keywords={'moving': moving}, ) moved_image = moving.__class__(moved, self.reference.affine, moving.header) moved_image.header.set_data_dtype(output_dtype) return moved_image
def reproj(self): """ Reproject from sample / beam to x / y and return new array. """ c = int(512 * np.sin(np.deg2rad(14.5))) rpdata = ndimage.geometric_transform(self.data, self._cart2pol, output_shape=(512, 2 * c), extra_keywords={'c': c}) rpdata = np.flipud(rpdata) return rpdata
def elastic_transform(self,xval,sigma,alpha): field_x = np.random.rand(xval.shape[0],xval.shape[1]) * 2. - 1. field_y = np.random.rand(xval.shape[0],xval.shape[1]) * 2. - 1. convolved_field_x = ni.filters.gaussian_filter(field_x,sigma) convolved_field_y = ni.filters.gaussian_filter(field_y,sigma) convolved_field_x = convolved_field_x * alpha / max(abs(convolved_field_x.flatten())) convolved_field_y = convolved_field_y * alpha / max(abs(convolved_field_y.flatten())) def mapping(coords): x,y = coords return (x+convolved_field_x[x,y],y+convolved_field_y[x,y]) return ni.geometric_transform(xval,mapping)
def test_geometric_transform_vs_padded(self, order, mode): x = numpy.arange(144, dtype=float).reshape(12, 12) def mapping(x): return (x[0] - 0.4), (x[1] + 2.3) # Manually pad and then extract center after the transform to get the # expected result. npad = 24 pad_mode = ndimage_to_numpy_mode.get(mode) xp = numpy.pad(x, npad, mode=pad_mode) center_slice = tuple([slice(npad, -npad)] * x.ndim) expected_result = ndimage.geometric_transform( xp, mapping, mode=mode, order=order)[center_slice] assert_allclose( ndimage.geometric_transform(x, mapping, mode=mode, order=order), expected_result, rtol=1e-7, )
def polar_warp(im,sz,r): #""" Warp an image to a square polar version. """ h,w = im.shape[:2] def polar_2_rect(xy): #""" Convert polar coordinates to coordinates in # the original image for geometric_transform. """ x,y = float(xy[1]),float(xy[0]) theta = 0.5*arctan2(x-sz/2,y-sz/2) R = sqrt( (x-sz/2)*(x-sz/2) + (y-sz/2)*(y-sz/2) ) - r return (2*h*R/(sz-2*r),w/2+theta*w/pi+pi/2) # if color image, warp each channel, otherwise there's just one if len(im.shape)==3: warped = zeros((sz,sz,3)) for i in range(3): warped[:,:,i] = geometric_transform(im[:,:,i],polar_2_rect,output_shape=(sz,sz),mode='nearest') else: warped = geometric_transform(im,polar_2_rect,output_shape=(sz,sz),mode='nearest') return warped
def deformBothAugment(img, mask, defrange=5): ''' Deform the central parts of the image/mask pair using interpolated randomized deformation. This is a particularly slow implementation of this concept, however it produces good results and other versions are still too slow to use online during training anyway. ''' grid = np.zeros((4, 4, 2), int) y = np.linspace(0, img.shape[0], grid.shape[0]) x = np.linspace(0, img.shape[1], grid.shape[1]) grid[1:3, 1:3, :] = 2 * defrange * np.random.random_sample( (2, 2, 2)) - defrange interx = interp2d(x, y, grid[..., 0], 'linear') intery = interp2d(x, y, grid[..., 1], 'linear') xargs = (interx, intery) return geometric_transform(img, mapping, extra_arguments=xargs), geometric_transform( mask, mapping, extra_arguments=xargs)
def scene (ag, s, gpix): ag = [ag] if ag.ndim==1 else ag aoff = np.zeros((2,s.shape[0],s.shape[1])) for g in ag: u,alpha,pot = lens(g,[],gpix) aoff[0] += alpha[0] aoff[1] += alpha[1] xoff,yoff = np.meshgrid (np.arange(s.shape[0],dtype='float'),\ np.arange(s.shape[1],dtype='float')) xoff -= aoff[0] yoff -= aoff[1] return ndimage.geometric_transform(s,shift_func,extra_arguments=(xoff,yoff))
def test_geometric_transform24(self, order): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x, a, b): return (a, x[0] * b) out = ndimage.geometric_transform( data, mapping, (2,), order=order, extra_arguments=(1,), extra_keywords={'b': 2}) assert_array_almost_equal(out, [5, 7])
def transform2D(I, q): #q is a four-tuple: (x,y,theta,scale) def shiftFn(x, c0, q0): #( original pixel coordinates , image centroid , rigid parameters ) c = c0[1],c0[0] q = -q0[1], -q0[0], q0[2] s = 1.0/q0[3] cq3,sq3 = cos(q[2]) , sin(q[2]) xp0 = c[0] + q[0]*cq3 - q[1]*sq3 +s*x[0]*cq3 -x[1]*sq3 -s*c[0]*cq3 +c[1]*sq3 xp1 = c[1] + q[0]*sq3 + q[1]*cq3 +x[0]*sq3 +s*x[1]*cq3 -c[0]*sq3 -s*c[1]*cq3 return xp0, xp1 c = 0.5*I.shape[1], 0.5*I.shape[0] I = ndimage.geometric_transform(I, shiftFn, order=1, extra_arguments=(c,q)) return I
def _findxycenter(hdr, im,ext,log): def xy_tran(out): """ Function to transform blue coordinates to red frame coordinates """ xref = out[1] - 990.5897 yref = out[0] - 37.82109 x = -0.9985259*xref - 0.0178984*yref y = -0.0181331*xref + 0.9991414*yref return y,x #hdr = pf.getheader(file) #im = pf.getdata(file) xcen = hdr.get('xcen') ycen = hdr.get('ycen') if (xcen == None): #ratio,xc,yc = peak2halo('',image=im) #xcen = xc #ycen = yc #if (xcen < 0 or ycen < 0): if True: if ext == 2: # register blue frame to red's frame coordinate system im = nd.geometric_transform (im,xy_tran) try: ndis.display(im,zscale=False) except IOError,err: sys.stderr.write('\n ***** ERROR: %s Start DS9.\n' % str(err)) sys.exit(1) print " Mark center with left button, then use 'q' to continue, 's' to skip." cursor = ndis.readcursor(sample=0) cursor = cursor.split() if cursor[3] == 's': hdr.update("XCEN",-1, "Start mask x-center") hdr.update("YCEN",-1, "Start mask y-center") updated = True print '\nFrame skipped... ****Make sure not to use it in your science script. ***\n' #return updated,xcen,ycen,im return xcen,ycen,im x1 = float(cursor[0]) y1 = float(cursor[1]) xcen,ycen = gcentroid(im, x1,y1,9) xcen = xcen[0] ycen = ycen[0] hdr.update("XCEN",xcen, "Start mask x-center") hdr.update("YCEN",ycen, "Start mask y-center") log.info(' (%.2f,%.2f) :: ' % (xcen,ycen)+('red','blue')[ext-1])
def transform(self,im): """ Return the transform of the blue frame to the reference coordinate system of the red. """ cref = self.gmo.fitObj def gfunc(out): xref = out[1] yref = out[0] x = cref.a + cref.b*xref + cref.c*yref y = cref.d + cref.e*xref + cref.f*yref return y,x return nd.geometric_transform(im, gfunc)
def calculate_Population_fitness(self, part): # (h,w) DomBlockSize = (16,16) RanBlockSize = (8,8) max_fitness = 1000000000 ranking = [] for chrom in part: # genes gen_x_dom = chrom[0:9] gen_y_dom = chrom[9:18] gen_flip = chrom[18:21] # fenotypes fen_xdom = int(gen_x_dom,2) # 2 for binary representation fen_ydom = int(gen_y_dom,2) fen_flip = int(gen_flip,2) try: DomBlk = self.Dom[fen_ydom:fen_ydom+DomBlockSize[0] ,fen_xdom:fen_xdom+DomBlockSize[1]] except: return "DomBlkError" try: DomBlk_hex = rgb2hex(DomBlk.copy()) except: return "rgb2hexError" try: temp = get_scaled.geometric_transform(DomBlk_hex, resize_func, output_shape=RanBlockSize) except: return "transformError" try: DomBlk_subsampled = get_dihedrical_transf(temp,fen_flip) except: return "dihedrTransformError" #p,q = calc_massic(DomBlk_subsampled,rngBlk) try: MSE = self.calculate_mse(DomBlk_subsampled) except MSEError,E: return E.reason try: rank = min(1/MSE,max_fitness) except ZeroDivisionError: rank = max_fitness heappush(ranking,(rank,chrom))
def polar_warp(im, sz, r): # Deformar una imagen para una versión polar cuadrada h, w = im.shape[:2] def polar_2_rect(xy): # Convertir coordenadas polares a en # la imagen original para transformar geométrica x, y = float(xy[1]), float(xy[0]) theta = 0.5 * arctan2(x - sz / 2, y - sz / 2) R = sqrt((x - sz / 2) * (x - sz / 2) + (y - sz / 2) * (y - sz / 2)) - r return (2 * h * R / (sz - 2 * r), w / 2 + theta * w / pi + pi / 2) # color de la imagen se deforma cada canal, si no hay una sola if len(im.shape) == 3: warped = zeros((sz, sz, 3)) for i in range(3): warped[:, :, i] = geometric_transform(im[:, :, i], polar_2_rect, output_shape=(sz, sz), mode='nearest') else: warped = geometric_transform(im, polar_2_rect, output_shape=(sz, sz), mode='nearest') return warped
def get_phenotype(chrom, Dom,DomBlockSize, RanBlockSize ): gen_x_dom = chrom[0:9] gen_y_dom = chrom[9:18] gen_flip = chrom[18:21] # fenotypes fen_xdom = int(gen_x_dom,2) # 2 for binary representation fen_ydom = int(gen_y_dom,2) fen_flip = int(gen_flip,2) DomBlk = Dom[fen_ydom:fen_ydom+DomBlockSize[0] ,fen_xdom:fen_xdom+DomBlockSize[1]] DomBlk_hex = rgb2hex(DomBlk.copy()) temp = get_scaled.geometric_transform(DomBlk_hex, resize_func, output_shape=RanBlockSize) DomBlk_subsampled = get_dihedrical_transf(temp,fen_flip) return DomBlk_subsampled
def op(self, img): jmg = img.copy() # Apply transformation to corners to guess bounding box sz = jmg.im.shape c = np.array([[0,0,sz[0],sz[0]],[0,sz[1],0,sz[1]]]) d = self.ini.xf(c) bx = tuple(d.max(1)) # Apply transformation to each channel for k in range(jmg.im.shape[2]): jmg.im[...,k] = si.geometric_transform(jmg.im[...,k], self.ini.xf, output_shape=bx) return jmg
def radial_extrusion(array, center=None): """ Create a radial extrusion from one-dimensional array passed as an argument. If not specified the center of rotation will be set to the center of array. """ inshape = array.shape assert len(inshape) == 1 center = center or inshape[0] / 2. outxs = max(inshape[0] - center, center) * 2 outys = outxs def out2in((outx, outy)): rho = ((outx-center) ** 2 + (outy-center) ** 2) ** .5 return (center + rho, ) extrusion = geometric_transform(array, out2in, (outxs, outys)) return extrusion
def test_boundaries(self): "boundary modes" def shift(x): return (x[0] + 0.5,) data = numpy.array([1,2,3,4.]) expected = { # 'constant': [1.5,2.5,3.5,-1,-1,-1,-1], 'wrap': [1.5,2.5,3.5,3.5,1.5,2.5,3.5], # 'mirror': [1.5,2.5,3.5,3.5,2.5,1.5,1.5], # 'nearest': [1.5,2.5,3.5,4,4,4,4] } for mode in expected: assert_array_equal(expected[mode], ndimage.geometric_transform(data,shift, cval=-1,mode=mode, output_shape=(7,), order=1))
def get_polar(array, interpolation=0, reverse=False): """ Returns a new array with the logpolar transfamation of array. Interpolation can be: 0 Near 1 Linear 2 Bilineal 3 Cubic 4 5 """ assert interpolation in range(6) rows, cols = array.shape row0 = rows / 2. col0 = cols / 2. theta_scalar = tau / cols max_radius = (row0 ** 2 + col0 ** 2) ** .5 rho_scalar = max_radius / cols def cart2pol(dst_coords): theta, rho = dst_coords rho = rho * rho_scalar theta = np.pi / 2 - theta * theta_scalar row_from = rho * cos(theta) + row0 col_from = rho * sin(theta) + col0 return row_from, col_from def pol2cart(dst_coords): xindex, yindex = dst_coords x = xindex - col0 y = yindex - row0 r = np.sqrt(x ** 2 + y ** 2) / rho_scalar theta = np.arctan2(y, x) theta_index = np.round((theta + np.pi) * cols / tau) return theta_index, r trans = pol2cart if reverse else cart2pol polar = geometric_transform(array, trans, array.shape, order=interpolation) return polar
def frget(d,h,i,uvw,times,maxoff,fsiz,dofilt): tdec = h['crval'][h['ctype'].index('DEC')] nc = h['naxis'][h['ctype'].index('FREQ')]*h['naxis'][h['ctype'].index('IF')] chwid = h['cdelt'][h['ctype'].index('FREQ')] fring = abs(fft.fftshift(fft.fft2(d))) fring = fring_filter(fring) if dofilt else fring alpha,beta,gamma,delta = frd2xy (uvw[i],tdec,chwid,nc,times[-1]-times[0]) xoff,yoff = np.meshgrid(np.arange(fring.shape[1],dtype='float'),\ np.arange(fring.shape[0],dtype='float')) xoff -= 0.5*fring.shape[1]; yoff -= 0.5*fring.shape[0] det = 1.0/(alpha*delta-beta*gamma) xp,yp = det*(delta*xoff-beta*yoff), det*(-gamma*xoff+alpha*yoff) maxoff = np.deg2rad(maxoff) if maxoff==0.0: maxoff = max(xp.max(),-xp.min(),yp.max(),-yp.min()) mat = np.asarray(np.meshgrid(np.arange(float(fsiz)),np.arange(float(fsiz)))) mat = maxoff*(mat-0.5*fsiz)/(0.5*fsiz) px,py = alpha*mat[0]+beta*mat[1],gamma*mat[0]+delta*mat[1] fmap = ndimage.geometric_transform(fring,shift_func,\ output_shape=(fsiz,fsiz),extra_arguments=(px,py,fring.shape)).T fmap = np.fliplr (fmap) # HA -> RA, flip about centre return fmap,np.rad2deg(maxoff)
def show_chrom(chrom, Dom, DomBlockSize ): RanBlockSize = (8,8) gen_x_dom = chrom[0:9] gen_y_dom = chrom[9:18] gen_flip = chrom[18:21] # fenotypes fen_xdom = int(gen_x_dom,2) # 2 for binary representation fen_ydom = int(gen_y_dom,2) fen_flip = int(gen_flip,2) DomBlk = Dom[fen_ydom:fen_ydom+DomBlockSize[0] ,fen_xdom:fen_xdom+DomBlockSize[1]] DomBlk_hex = rgb2hex(DomBlk.copy()) temp = get_scaled.geometric_transform(DomBlk_hex, resize_func, output_shape=RanBlockSize) DomBlk_subsampled = get_dihedrical_transf(temp,fen_flip) DomBlk_subsampled = DomBlk_subsampled.copy() pilImage = Image.frombuffer('RGBA',DomBlk_subsampled.shape,DomBlk_subsampled,'raw','RGBA',0,1) #for rgba #pilImage = Image.frombuffer('RGBA',DomBlk_hex.shape,DomBlk_hex,'raw','RGBA',0,1) #for rgba imshow(pilImage.transpose(1))
def unwrap(im): shape = np.shape(im) h, w = shape[0], shape[1] center = ( ((shape[0]-1) / 2.0), ((shape[1]-1)/2.0) ) cy = center[0] cx = center[1] rheight = np.hypot(np.max(shape[0])/2.0, np.max(shape[1])/2.0) def rect_to_polar(xy): x,y = float(xy[1]),float(xy[0]) R = x theta = (y / 360.0) * np.pi * 2 # Convert x & y into pixel coordinates x = R * np.cos(theta) + cx y = R * np.sin(theta) + cy return x, y return geometric_transform(im, rect_to_polar ,output_shape=(360, rheight), order = 5, mode='constant')
# mask nan values, so they will not appear on plot Zm = np.ma.masked_where(np.isnan(Z), Z) Omega = 1.0 Vortensity = (dZdX - dZdY + 2*Omega)/Zm smooth_scale = (outer_radius - inner_radius) / \ radial_zones / delta_x / 1.5 Vortensity = gaussian_filter(Vortensity, smooth_scale, mode='nearest') if (num == 0): Vortensity0 = Vortensity print("Doing geometric transformation to R-theta plane...") # create polar-coordinate array Vortensity_polar = geometric_transform(Vortensity.T, cartesian2polar, output_shape=(Vortensity.T.shape[0], Vortensity.T.shape[0]), extra_keywords={'inputshape': Vortensity.T.shape, 'origin': (Vortensity.T.shape[0]/2, Vortensity.T.shape[1]/2)}) if (num == 0): Vortensity0_polar = Vortensity_polar #################################################################### # plot if not (skip_cartesian): ax = fig.add_subplot(1, len(dir_array), count_dir) divider = make_axes_locatable(ax) cmap = cm.get_cmap('jet') im = ax.imshow(np.log10(Vortensity/Vortensity0), origin='lower', vmin=min_scale, vmax=max_scale, extent=[rangeX[0], rangeX[1], rangeY[0], rangeY[1]], cmap=cmap)
def make_mosaic(struct, gap, xshift, yshift, rotation, interp_type='linear', boundary='constant', constant=0, geotran=True, fill=False, cleanup=True, log=None, verbose=False): """Given a SALT image struct, combine each of the individual amplifiers and apply the geometric CCD transformations to the image """ # get the name of the file infile = saltkey.getimagename(struct[0], base=True) outpath = './' # identify instrument instrume, keyprep, keygain, keybias, keyxtalk, keyslot = \ saltkey.instrumid(struct) # how many amplifiers? nsciext = saltkey.get('NSCIEXT', struct[0]) nextend = saltkey.get('NEXTEND', struct[0]) nccds = saltkey.get('NCCDS', struct[0]) amplifiers = nccds * 2 if nextend > nsciext: varframe = True else: varframe = False # CCD geometry coefficients if (instrume == 'RSS' or instrume == 'PFIS'): xsh = [0., xshift[0], 0., xshift[1]] ysh = [0., yshift[0], 0., yshift[1]] rot = [0., rotation[0], 0., rotation[1]] elif instrume == 'SALTICAM': xsh = [0., xshift[0], 0.] ysh = [0., yshift[0], 0.] rot = [0., rotation[0], 0] # how many extensions? nextend = saltkey.get('NEXTEND', struct[0]) # CCD on-chip binning xbin, ybin = saltkey.ccdbin(struct[0]) # create temporary primary extension outstruct = [] outstruct.append(struct[0]) # define temporary FITS file store tiled CCDs tilefile = saltio.tmpfile(outpath) tilefile += 'tile.fits' if varframe: tilehdu = [None] * (3 * int(nsciext / 2) + 1) else: tilehdu = [None] * int(nsciext / 2 + 1) tilehdu[0] = fits.PrimaryHDU() #tilehdu[0].header = struct[0].header if log: log.message('', with_stdout=verbose) # iterate over amplifiers, stich them to produce file of CCD images for i in range(int(nsciext / 2)): hdu = i * 2 + 1 # amplifier = hdu%amplifiers # if (amplifier == 0): amplifier = amplifiers # read DATASEC keywords datasec1 = saltkey.get('DATASEC', struct[hdu]) datasec2 = saltkey.get('DATASEC', struct[hdu + 1]) xdsec1, ydsec1 = saltstring.secsplit(datasec1) xdsec2, ydsec2 = saltstring.secsplit(datasec2) # read images imdata1 = saltio.readimage(struct, hdu) imdata2 = saltio.readimage(struct, hdu + 1) # tile 2n amplifiers to yield n CCD images outdata = numpy.zeros((ydsec1[1] + abs(ysh[i + 1] / ybin), xdsec1[1] + xdsec2[1] + abs(xsh[i + 1] / xbin)), numpy.float32) # set up the variance frame if varframe: vardata = outdata.copy() vdata1 = saltio.readimage(struct, struct[hdu].header['VAREXT']) vdata2 = saltio.readimage(struct, struct[hdu + 1].header['VAREXT']) bpmdata = outdata.copy() bdata1 = saltio.readimage(struct, struct[hdu].header['BPMEXT']) bdata2 = saltio.readimage(struct, struct[hdu + 1].header['BPMEXT']) x1 = xdsec1[0] - 1 if x1 != 0: msg = 'The data in %s have not been trimmed prior to mosaicking.' \ % infile log.error(msg) if xsh[i + 1] < 0: x1 += abs(xsh[i + 1] / xbin) x2 = x1 + xdsec1[1] y1 = ydsec1[0] - 1 if ysh[i + 1] < 0: y1 += abs(ysh[i + 1] / ybin) y2 = y1 + ydsec1[1] outdata[y1:y2, x1:x2] =\ imdata1[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] if varframe: vardata[y1:y2, x1:x2] =\ vdata1[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] bpmdata[y1:y2, x1:x2] =\ bdata1[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] x1 = x2 x2 = x1 + xdsec2[1] y1 = ydsec2[0] - 1 if ysh[i + 1] < 0: y1 += abs(ysh[i + 1] / ybin) y2 = y1 + ydsec2[1] outdata[y1:y2, x1:x2] =\ imdata2[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] if varframe: vardata[y1:y2, x1:x2] =\ vdata2[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] bpmdata[y1:y2, x1:x2] =\ bdata2[ydsec1[0] - 1:ydsec1[1], xdsec1[0] - 1:xdsec1[1]] # size of new image naxis1 = str(xdsec1[1] + xdsec2[1]) naxis2 = str(ydsec1[1]) # add image and keywords to HDU list tilehdu[i + 1] = fits.ImageHDU(outdata) tilehdu[i + 1].header = struct[hdu].header #tilehdu[ # i + 1].header['DATASEC'] = '[1:' + naxis1 + ',1:' + naxis2 + ']' if varframe: vext = i + 1 + int(nsciext / 2.) tilehdu[vext] = fits.ImageHDU(vardata) #tilehdu[vext].header = struct[struct[hdu].header['VAREXT']].header #tilehdu[vext].header[ # 'DATASEC'] = '[1:' + naxis1 + ',1:' + naxis2 + ']' bext = i + 1 + 2 * int(nsciext / 2.) tilehdu[bext] = fits.ImageHDU(bpmdata) #tilehdu[bext].header = struct[struct[hdu].header['BPMEXT']].header #tilehdu[bext].header[ # 'DATASEC'] = '[1:' + naxis1 + ',1:' + naxis2 + ']' # image tile log message #1 if log: message = os.path.basename(infile) + '[' + str(hdu) + '][' message += str(xdsec1[0]) + ':' + str(xdsec1[1]) + ',' message += str(ydsec1[0]) + ':' + str(ydsec1[1]) + '] --> ' message += os.path.basename(tilefile) + '[' + str(i + 1) + '][' message += str(xdsec1[0]) + ':' + str(xdsec1[1]) + ',' message += str(ydsec1[0]) + ':' + str(ydsec1[1]) + ']' log.message(message, with_stdout=verbose, with_header=False) message = os.path.basename(infile) + '[' + str(hdu + 1) + '][' message += str(xdsec1[0]) + ':' + str(xdsec1[1]) + ',' message += str(ydsec1[0]) + ':' + str(ydsec1[1]) + '] --> ' message += os.path.basename(tilefile) + '[' + str(i + 1) + '][' message += str(xdsec1[1] + 1) + ':' + \ str(xdsec1[1] + xdsec2[1]) + ',' message += str(ydsec2[0]) + ':' + str(ydsec2[1]) + ']' log.message(message, with_stdout=verbose, with_header=False) # write temporary file of tiled CCDs hdulist = fits.HDUList(tilehdu) hdulist.writeto(tilefile) # iterate over CCDs, transform and rotate images yrot = [None] * 4 xrot = [None] * 4 tranfile = [' '] tranhdu = [0] if varframe: tranfile = [''] * (3 * int(nsciext / 2) + 1) tranhdu = [0] * (3 * int(nsciext / 2) + 1) else: tranfile = [''] * int(nsciext / 2 + 1) tranhdu = [0] * int(nsciext / 2 + 1) # this is hardwired for SALT where the second CCD is considered the # fiducial for hdu in range(1, int(nsciext / 2 + 1)): tranfile[hdu] = saltio.tmpfile(outpath) tranfile[hdu] += 'tran.fits' if varframe: tranfile[hdu + nccds] = saltio.tmpfile(outpath) + 'tran.fits' tranfile[hdu + 2 * nccds] = saltio.tmpfile(outpath) + 'tran.fits' ccd = hdu % nccds if (ccd == 0): ccd = nccds # correct rotation for CCD binning yrot[ccd] = rot[ccd] * ybin / xbin xrot[ccd] = rot[ccd] * xbin / ybin dxshift = xbin * int(float(int(gap) / xbin) + 0.5) - gap # transformation using geotran IRAF task # if (ccd == 1): if (ccd != 2): if geotran: message = '\nSALTMOSAIC -- geotran ' + tilefile + \ '[' + str(ccd) + '] ' + tranfile[hdu] message += ' \"\" \"\" xshift=' + \ str((xsh[ccd] + (2 - ccd) * dxshift) / xbin) + ' ' message += 'yshift=' + \ str(ysh[ccd] / ybin) + ' xrotation=' + str(xrot[ccd]) + ' ' message += 'yrotation=' + \ str(yrot[ccd]) + ' xmag=1 ymag=1 xmin=\'INDEF\'' message += 'xmax=\'INDEF\' ymin=\'INDEF\' ymax=\'INDEF\' ' message += 'ncols=\'INDEF\' ' message += 'nlines=\'INDEF\' verbose=\'no\' ' message += 'fluxconserve=\'yes\' nxblock=2048 ' message += 'nyblock=2048 interpolant=\'' + \ interp_type + '\' boundary=\'constant\' constant=0' log.message(message, with_stdout=verbose) yd, xd = tilehdu[ccd].data.shape ncols = 'INDEF' # ncols=xd+abs(xsh[ccd]/xbin) nlines = 'INDEF' # nlines=yd+abs(ysh[ccd]/ybin) geo_xshift = xsh[ccd] + (2 - ccd) * dxshift / xbin geo_yshift = ysh[ccd] / ybin iraf.images.immatch.geotran(tilefile + "[" + str(ccd) + "]", tranfile[hdu], "", "", xshift=geo_xshift, yshift=geo_yshift, xrotation=xrot[ccd], yrotation=yrot[ccd], xmag=1, ymag=1, xmin='INDEF', xmax='INDEF', ymin='INDEF', ymax='INDEF', ncols=ncols, nlines=nlines, verbose='no', fluxconserve='yes', nxblock=2048, nyblock=2048, interpolant="linear", boundary="constant", constant=0) if varframe: var_infile = tilefile + "[" + str(ccd + nccds) + "]" iraf.images.immatch.geotran(var_infile, tranfile[hdu + nccds], "", "", xshift=geo_xshift, yshift=geo_yshift, xrotation=xrot[ccd], yrotation=yrot[ccd], xmag=1, ymag=1, xmin='INDEF', xmax='INDEF', ymin='INDEF', ymax='INDEF', ncols=ncols, nlines=nlines, verbose='no', fluxconserve='yes', nxblock=2048, nyblock=2048, interpolant="linear", boundary="constant", constant=0) var2_infile = tilefile + "[" + str(ccd + 2 * nccds) + "]" iraf.images.immatch.geotran(var2_infile, tranfile[hdu + 2 * nccds], "", "", xshift=geo_xshift, yshift=geo_yshift, xrotation=xrot[ccd], yrotation=yrot[ccd], xmag=1, ymag=1, xmin='INDEF', xmax='INDEF', ymin='INDEF', ymax='INDEF', ncols=ncols, nlines=nlines, verbose='no', fluxconserve='yes', nxblock=2048, nyblock=2048, interpolant="linear", boundary="constant", constant=0) # open the file and copy the data to tranhdu tstruct = fits.open(tranfile[hdu]) tranhdu[hdu] = tstruct[0].data tstruct.close() if varframe: tranhdu[ hdu + nccds] = fits.open( tranfile[ hdu + nccds])[0].data tranhdu[ hdu + 2 * nccds] = fits.open( tranfile[ hdu + 2 * nccds])[0].data else: log.message( "Transform CCD #%i using dx=%s, dy=%s, rot=%s" % (ccd, xsh[ccd] / 2.0, ysh[ccd] / 2.0, xrot[ccd]), with_stdout=verbose, with_header=False) tranhdu[hdu] = geometric_transform( tilehdu[ccd].data, tran_func, prefilter=False, order=1, extra_arguments=( xsh[ccd] / 2, ysh[ccd] / 2, 1, 1, xrot[ccd], yrot[ccd])) tstruct = fits.PrimaryHDU(tranhdu[hdu]) tstruct.writeto(tranfile[hdu]) if varframe: tranhdu[hdu + nccds] = geometric_transform( tilehdu[hdu + 3].data, tran_func, prefilter=False, order=1, extra_arguments=( xsh[ccd] / 2, ysh[ccd] / 2, 1, 1, xrot[ccd], yrot[ccd])) tranhdu[hdu + 2 * nccds] = geometric_transform( tilehdu[hdu + 6].data, tran_func, prefilter=False, order=1, extra_arguments=( xsh[ccd] / 2, ysh[ccd] / 2, 1, 1, xrot[ccd], yrot[ccd])) else: log.message( "Transform CCD #%i using dx=%s, dy=%s, rot=%s" % (ccd, 0, 0, 0), with_stdout=verbose, with_header=False) tranhdu[hdu] = tilehdu[ccd].data if varframe: tranhdu[hdu + nccds] = tilehdu[ccd + nccds].data tranhdu[hdu + 2 * nccds] = tilehdu[ccd + 2 * nccds].data # open outfile if varframe: outlist = 4 * [None] else: outlist = 2 * [None] #outlist[0] = struct[0].copy() outlist[0] = fits.PrimaryHDU() outlist[0].header = struct[0].header naxis1 = int(gap / xbin * (nccds - 1)) naxis2 = 0 for i in range(1, nccds + 1): yw, xw = tranhdu[i].shape naxis1 += xw + int(abs(xsh[ccd] / xbin)) + 1 naxis2 = max(naxis2, yw) outdata = numpy.zeros((naxis2, naxis1), numpy.float32) outdata.shape = naxis2, naxis1 if varframe: vardata = outdata * 0 bpmdata = outdata * 0 + 1 # iterate over CCDs, stich them to produce a full image hdu = 0 totxshift = 0 for hdu in range(1, nccds + 1): # read DATASEC keywords ydsec, xdsec = tranhdu[hdu].shape # define size and shape of final image # tile CCDs to yield mosaiced image x1 = int((hdu - 1) * (xdsec + gap / xbin)) + int(totxshift) x2 = xdsec + x1 y1 = int(0) y2 = int(ydsec) outdata[y1:y2, x1:x2] = tranhdu[hdu] totxshift += int(abs(xsh[hdu] / xbin)) + 1 if varframe: vardata[y1:y2, x1:x2] = tranhdu[hdu + nccds] bpmdata[y1:y2, x1:x2] = tranhdu[hdu + 2 * nccds] # make sure to cover up all the gaps include bad areas if varframe: baddata = (outdata == 0) baddata = nd.maximum_filter(baddata, size=3) bpmdata[baddata] = 1 # fill in the gaps if requested if fill: if varframe: outdata = fill_gaps(outdata, 0) else: outdata = fill_gaps(outdata, 0) # add to the file outlist[1] = fits.ImageHDU(outdata) if varframe: outlist[2] = fits.ImageHDU(vardata,name='VAR') outlist[3] = fits.ImageHDU(bpmdata,name='BPM') # create the image structure outstruct = fits.HDUList(outlist) # update the head informaation # housekeeping keywords saltkey.put('NEXTEND', 2, outstruct[0]) saltkey.new('EXTNAME', 'SCI', 'Extension name', outstruct[1]) saltkey.new('EXTVER', 1, 'Extension number', outstruct[1]) if varframe: saltkey.new('VAREXT', 2, 'Variance frame extension', outstruct[1]) saltkey.new('BPMEXT', 3, 'BPM Extension', outstruct[1]) try: saltkey.copy(struct[1], outstruct[1], 'CCDSUM') except: pass # Add keywords associated with geometry saltkey.new('SGEOMGAP', gap, 'SALT Chip Gap', outstruct[0]) c1str = '{:3.2f} {:3.2f} {:3.4f}'.format(xshift[0], yshift[0], rotation[0]) saltkey.new('SGEOM1', c1str, 'SALT Chip 1 Transform', outstruct[0]) c2str = '{:3.2f} {:3.2f} {:3.4f}'.format(xshift[1], yshift[1], rotation[1]) saltkey.new('SGEOM2', c2str, 'SALT Chip 2 Transform', outstruct[0]) # WCS keywords saltkey.new('CRPIX1', 0, 'WCS: X reference pixel', outstruct[1]) saltkey.new('CRPIX2', 0, 'WCS: Y reference pixel', outstruct[1]) saltkey.new( 'CRVAL1', float(xbin), 'WCS: X reference coordinate value', outstruct[1]) saltkey.new( 'CRVAL2', float(ybin), 'WCS: Y reference coordinate value', outstruct[1]) saltkey.new('CDELT1', float(xbin), 'WCS: X pixel size', outstruct[1]) saltkey.new('CDELT2', float(ybin), 'WCS: Y pixel size', outstruct[1]) saltkey.new('CTYPE1', 'pixel', 'X type', outstruct[1]) saltkey.new('CTYPE2', 'pixel', 'Y type', outstruct[1]) # cleanup temporary files if cleanup: for tfile in tranfile: if os.path.isfile(tfile): saltio.delete(tfile) if os.path.isfile(tilefile): status = saltio.delete(tilefile) # return the file return outstruct
def r_inverted(z): if z == 1: return 0 # infty return (1 + z) / (1 - z) # t(z) = kz def t_inverted(z): return z / k def image_transform(point): z = result_image_to_plane(point[1], point[0]) z = r_inverted(z) z = t_inverted(z) x, y = polar_grid_to_init_image(z) return y, x, point[2] for i in range(0, nit): transformed_image = Image.fromarray( geometric_transform( init_image, image_transform, output_shape=(result_image_height, result_image_width, 4), order=1 ) ) result_image = Image.new("RGBA", back_image.size) result_image.paste(back_image, (0, 0)) result_image.paste(transformed_image, (0, 0), transformed_image) result_image.save(str(i) + ".png") k *= delta_k
b = (u, 1j, -1j, u) nit = 10 def c(k, i): q = (x + 1)**(1.0 * i / k) w = (x - 1)**(1.0 * i / k) t = (q + w) / 2.0 s = (q - w) / 2.0 return (t, s, s, t) def d(k, i): q = (u + 1)**(1.0 * i / k) w = (u - 1)**(1.0 * i / k) t = (q + w) / 2.0 s = (q - w) / 2.0 return (t, 1j * s, -1j*s, t) transforms = iterate_transforms([a, b], 3) for i in range(nit): result_image = Image.new("RGBA", (result_image_size, result_image_size), color=(127, 0, 255)) for f in transforms: f_ = invert(compose(f, c(nit, i))) transformed_image = Image.fromarray( geometric_transform(init_image, image_transform(f_), output_shape=(result_image_size, result_image_size, 4), order=1)) result_image.paste(transformed_image, (0, 0), transformed_image) result_image.show() result_image.save(str(i) + ".png")
# Load Stokes parameters St = [N.loadtxt(datapath + 'B1_groove_S{}.txt'.format(count))[:, ::-1] for count in range(4)] St[1] *= -1 # crap, correct for different definition of handedness xlen, ylen = St[0].shape xc, yc = 151, 160 rin, rout = 123, 136 polarshape = (rout, 90) averages = [] for image in St: extra_keywords = {'centercoords': (xc, yc), 'ntheta': polarshape[1], 'nr': polarshape[0], 'rmax': rout} transformed = ndimage.geometric_transform(image, polarcoords, output_shape=polarshape, order=1, extra_keywords=extra_keywords) averages += [transformed[rin:rout, :].mean(0)] # Blank out overexposed points for avg in averages: avg[19:23] = N.NaN theta = N.linspace(0, 360, num=polarshape[1], endpoint=True) Ip = N.sqrt((averages[1] ** 2.0 + averages[2] ** 2.0 + averages[3] ** 2.0) / averages[0] ** 2.0) modL = N.sqrt((averages[1] ** 2.0 + averages[2] ** 2.0) / averages[0] ** 2.0) widths = N.sqrt(0.5 * (Ip + modL)) heights = N.sqrt(0.5 * (Ip - modL)) angles = 0.5 * N.arctan2(averages[2], averages[1]) * 180.0 / N.pi lhcp_mask = ((averages[3] / averages[0]) < -0.1) rhcp_mask = ((averages[3] / averages[0]) > 0.1) lin_mask = ~(lhcp_mask | rhcp_mask)
if theta < 0: theta = theta + 360 r = math.sqrt(x*x+y*y) bx = int(theta) br = int(r * maxrange) return (bx, br) file = os.path.basename(my_example_h5_file) tokens = file.split('.') moment = tokens[2] forig = tokens[0] elevation = tokens[1] with h5py.File(my_example_h5_file,'r') as hf: print('List of arrays in this file: \n', hf.keys()) data = hf.get('dataset1') np_data = np.array(data.get("data1/data")) print('Shape of the array: \n', np_data.shape) maxrange = np_data.shape[1] * 1.0 reprojected = geometric_transform(np_data, cartesian2bscope, output_shape=(np_data.shape[1]*2,np_data.shape[1]*2)) reprojected = np.flip(np.rot90(reprojected, k = 2), axis=1) fname = forig + '.' + elevation + '.' + moment +'_polar.png' plt = mpl.figure(figsize=(15, 15), dpi=75, frameon=False) im = mpl.imshow(reprojected, interpolation='nearest', cmap="afmhot") mpl.axis('off') mpl.title(fname, fontsize=18) plt.savefig(fname, bbox_inches='tight') #subprocess.call("mogrify -fuzz 25% -trim -border 25 -bordercolor white +repage " + fname, shell=True) print("Written: "+fname)