def get_error(self, data, model): nr1 = beads.transform(model, self.r0[data]) err_per_point = numpy.array([ numpy.linalg.norm(self.r1[data[i]] - nr1[i]) for i in range(len(data)) ]) return err_per_point
def calculateFinalWeightMatrices(params, stacks, axisOfRotation=1, sigmoidHalfWidthRelativeToImageSize=0.05, adaptiveCenterFile=None, sampleIntensityThreshold=15): # old function arguments: # params,size,spacings,isotropicSpacing,outShape=None,outSpacing=None,sigmoidHalfWidthRelativeToImageSize=0.05) """ :rtype : object - expects params and size, axisOfRotation, adaptiveCenterFile(sitk) relative to axes definition: (x,y,z) - rotation around x """ #origins = infoDict['origins'] #positions = infoDict['positions'] #spacing = infoDict['spacing'] #centerOfRotation = infoDict['centerOfRotation'] #axisOfRotation = infoDict['axisOfRotation'] #sizes = infoDict['sizes'] params = n.array(params) finalSize = n.ceil(stacks[0].GetSize()).astype(n.int64) # finalSpacing = n.array(stacks[0].GetSpacing()).astype(n.float64) # tmpMatrix = n.zeros((4,4)).astype(n.float) # tmpMatrix[:3,:3] = params[1][:9].reshape((3,3)) # direction = transformations.rotation_from_matrix(tmpMatrix)[1] axisOfRotation = n.argmax(n.abs(params[1][[0, 4, 8]])) print 'determining axis of rotation from parameters... %s' % axisOfRotation axes = range(3) axes.remove(axisOfRotation) firstAxis = axes[0] lastAxis = axes[1] def calcAngles(Y, Z): norm = n.sqrt(n.power(Y, 2) + n.power(Z, 2)) norm[norm == 0] = 0.001 angles = [] angles.append(n.arccos(Y / norm)) angles.append(2 * n.pi - n.arccos(Y / norm)) #angles.append(n.pi-n.arccos(-Y/norm)) #angles.append(n.pi+n.arccos(-Y/norm)) finalAngles = n.zeros(Y.shape, dtype=n.float64) #criteria = [(Y>=0)*(Z>=0),(Y>=0)*(Z<0),(Y<0)*(Z>=0),(Y<0)*(Z<0)] criteria = [(Z >= 0), (Z < 0)] for icrit, crit in enumerate(criteria): finalAngles[crit] = angles[icrit][crit] return finalAngles if adaptiveCenterFile == None: centers = n.array([[finalSize[lastAxis], finalSize[firstAxis]]]) / 2. else: print 'calculating stack centers for fusion weights (assuming sample intensity of >%s)' % sampleIntensityThreshold #adaptiveCenterFileSpacing = n.array(adaptiveCenterFile.GetSpacing()) centers = [] Z, Y = n.mgrid[0:finalSize[lastAxis], 0:finalSize[firstAxis]] Z, Y = sitk.GetImageFromArray(Y.astype( n.uint16)), sitk.GetImageFromArray(Z.astype(n.uint16)) for x in range(adaptiveCenterFile.GetSize()[axisOfRotation]): if axisOfRotation == 0: xImage = adaptiveCenterFile[x] elif axisOfRotation == 1: xImage = adaptiveCenterFile[:, x] elif axisOfRotation == 2: xImage = adaptiveCenterFile[:, :, x] #pdb.set_trace() Z.SetOrigin(xImage.GetOrigin()) Z.SetSpacing(xImage.GetSpacing()) Y.SetOrigin(xImage.GetOrigin()) Y.SetSpacing(xImage.GetSpacing()) xImage = sitk.Cast(xImage > sampleIntensityThreshold, 7 ) * 1000 + 0.01 #careful, could create overflow totalIntensity = sitk.SumProjection(sitk.SumProjection(xImage, 0), 1).GetPixel(0, 0) z = sitk.SumProjection( sitk.SumProjection(sitk.Cast(Z, 7) * xImage, 0), 1).GetPixel( 0, 0) / totalIntensity y = sitk.SumProjection( sitk.SumProjection(sitk.Cast(Y, 7) * xImage, 0), 1).GetPixel( 0, 0) / totalIntensity # totalIntensity = sitk.SumProjection(sitk.SumProjection(sitk.GetImageFromArray(n.ones(xImage.GetSize())),0),1).GetPixel(0,0) #pdb.set_trace() # z = sitk.SumProjection(sitk.SumProjection(Z,0),1).GetPixel(0,0)/totalIntensity # y = sitk.SumProjection(sitk.SumProjection(Y,0),1).GetPixel(0,0)/totalIntensity # tmp = sitk.GetArrayFromImage(xImage) # tmp[int(y),int(z)] = 2000 # plt.imshow(tmp) # plt.colorbar() # plt.show() center = [y, z] centers.append(center) # smoothen center line centers = n.array(centers) #centers = n.array([ndimage.gaussian_filter(centers[:,i],finalSize[[firstAxis,lastAxis][i]]/30.) for i in range(2)]) #centers = centers.swapaxes(0,1) # get angles refCenter = n.array(stacks[0].TransformIndexToPhysicalPoint( [int(i) for i in n.array(stacks[0].GetSize()) / 2.])) #origCenter = n.array([refCenter[i] for i in [lastAxis,firstAxis]]) bestAngles = [] refPoints = [] print 'refCenter %s' % refCenter refPoints.append(refCenter) for iparam, param in enumerate(params): # point2 is refCenter in rotated view point2 = beads.transform(param, [refCenter])[0] # shift point2 in z (positive here since later compared to positive again) point2[lastAxis] += 100 # transform back to reference view refPoint = beads.backTransform(param, [point2])[0] refPoints.append(refPoint) # calc direction vector refVector = refPoint - refCenter refVector = n.array([refVector[i] for i in [lastAxis, firstAxis]]) refVector = refVector / n.linalg.norm(refVector) # calc angle with respect to [1,1] angle = calcAngles(n.array([refVector[0]]), n.array([refVector[1]])) bestAngles.append(angle) #pdb.set_trace() refPoints = n.array(refPoints) # plt.plot(refPoints[:,0],refPoints[:,2],'o') # plt.show() zCenter = finalSize[[lastAxis, firstAxis]] / 2. lower = n.array([0, 0]) upper = finalSize[[lastAxis, firstAxis]] templateLower = lower - n.max(centers, 0) + zCenter templateUpper = upper - n.min(centers, 0) + zCenter print templateLower, templateUpper deltaplus = n.ceil(templateUpper - zCenter) deltaminus = n.ceil(zCenter - templateLower) templateSize = deltaminus + deltaplus Y, Z = n.mgrid[0:templateSize[0], 0:templateSize[1]] Y = Y - deltaminus[0] Z = Z - deltaminus[1] norm = n.sqrt(n.power(Y, 2) + n.power(Z, 2)) sigmoidHalfWidthInPixels = n.mean( finalSize[[firstAxis, lastAxis]]) * sigmoidHalfWidthRelativeToImageSize halfY = 0.9 # half width is defined as the x value corresponding to y=halfY norm[norm == 0] = 0.0001 sigmoidA = n.log(1. / halfY - 1.) / n.arctan( sigmoidHalfWidthInPixels / norm) finalAngles = calcAngles(Y, Z) # plt.imshow(finalAngles) # plt.title('finalAngles') # plt.colorbar() # plt.show() # add cameras here viewAngles = [] for i in range(len(bestAngles)): viewAngle = [] viewAngle.append(bestAngles[i]) viewAngle.append((bestAngles[i] + n.pi) % (2 * n.pi)) viewAngles.append(viewAngle) print viewAngles # calculate difference to ref angles weights = [] for iview, viewAngle in enumerate(viewAngles): tmp = n.min([ n.min([ n.abs(finalAngles - i), n.abs(2 * n.pi - n.abs(finalAngles - i)) ], 0) for i in viewAngle ], 0) weights.append(tmp.astype(n.float32)) # plt.imshow(weights[iview]) # plt.title('weights1 %s' %iview) # plt.colorbar() # plt.show() # #tifffile.imsave('/home/malbert/delme/test%s.tif' %(iview),weights[iview]) weightsDiff = [] for iview, view in enumerate(viewAngles): weightsDiff.append( n.min([ -weights[iview] + weights[i] for i in n.delete(range(len(viewAngles)), iview, 0) ], 0)) #tifffile.imsave('/home/malbert/delme/test%s.tif' %(iview),weightsDiff[iview]) #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weightsDiff[iview]),3),'/home/malbert/delme/test%s.tif' %(iview)) # plt.imshow(weightsDiff[iview]) # plt.title('weightsDiff1 %s' %iview) # plt.colorbar() # plt.show() for iview, view in enumerate(viewAngles): weightsDiff[iview] = (1 / (1 + n.exp(sigmoidA * (weightsDiff[iview])))) # plt.imshow(weightsDiff[iview]) # plt.title('weightsDiff2 %s' %iview) # plt.colorbar() # plt.show() #pdb.set_trace() #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weightsDiff[iview]*100),3),'/home/malbert/delme/test%s.tif' %(iview)) weights = [] weightsDiffSum = n.sum(weightsDiff, 0) for iview, view in enumerate(viewAngles): weights.append(weightsDiff[iview] / weightsDiffSum) #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weights[iview]*1000),3),'/home/malbert/delme/test%s.tif' %(iview)) #sitk.WriteImage(sitk.Cast(finalWeights[iview]*1000,3),'/home/malbert/delme/test0.tif') xWeights = [] for icenter, center in enumerate(centers): xWeight = [] for iview, view in enumerate(viewAngles): # pdb.set_trace() # plt.imshow(weights[iview]) # plt.title('test') # plt.colorbar() # plt.show() xW = sitk.GetImageFromArray(weights[iview]) #xW.SetOrigin((templateLower[0], templateLower[1])) xW.SetOrigin([0, 0]) tmpTransform = sitk.Transform(2, 1) tmpSize = finalSize[[lastAxis, firstAxis]].astype(n.int64) tmpSize = [int(i) for i in tmpSize[::-1]] tmpOrigin = n.array([-center[i] + deltaminus[i] for i in [1, 0]]) #pdb.set_trace() tmpTransform.SetParameters(tmpOrigin) #pdb.set_trace() xW = sitk.Resample( xW, tmpSize, tmpTransform, sitk.sitkLinear, #tmpOrigin ) #pdb.set_trace() xW = sitk.GetArrayFromImage(xW) xWeight.append(xW) # plt.imshow(xW) # plt.title('weights %s %s' %(iview,center)) # plt.colorbar() # plt.show() xWeights.append(xWeight) finalWeights = [] for i in range(len(params)): #finalWeights.append(sitk.GetImageFromArray(xWeights[0][i])) if adaptiveCenterFile is None: tmp = n.array([xWeights[0][i]] * finalSize[axisOfRotation]) else: tmp = n.array( [xWeights[j][i] for j in range(finalSize[axisOfRotation])]) if axisOfRotation == 0: numpyAxisOfRotation = 2 elif axisOfRotation == 1: numpyAxisOfRotation = 1 elif axisOfRotation == 2: numpyAxisOfRotation = 0 tmp = tmp.swapaxes(0, numpyAxisOfRotation) if numpyAxisOfRotation == 2: otherAxes = range(3) otherAxes.remove(numpyAxisOfRotation) tmp = tmp.swapaxes(otherAxes[0], otherAxes[1]) #tmp = tmp.swapaxes(0, 1).swapaxes(1, 2).astype(n.float32) tmp = tmp.astype(n.float32) finalWeights.append(sitk.GetImageFromArray(tmp)) #sitk.WriteImage(sitk.Cast(finalWeights[iview]*1000,3),'/home/malbert/delme/test.tif') return finalWeights
def get_error( self, data, model): nr1 = beads.transform(model,self.r0[data]) err_per_point = numpy.array([numpy.linalg.norm(self.r1[data[i]]-nr1[i]) for i in range(len(data))]) return err_per_point
def calculateFinalWeightMatrices(params, stacks, axisOfRotation=1, sigmoidHalfWidthRelativeToImageSize=0.05, adaptiveCenterFile=None, sampleIntensityThreshold=15 ): # old function arguments: # params,size,spacings,isotropicSpacing,outShape=None,outSpacing=None,sigmoidHalfWidthRelativeToImageSize=0.05) """ :rtype : object - expects params and size, axisOfRotation, adaptiveCenterFile(sitk) relative to axes definition: (x,y,z) - rotation around x """ #origins = infoDict['origins'] #positions = infoDict['positions'] #spacing = infoDict['spacing'] #centerOfRotation = infoDict['centerOfRotation'] #axisOfRotation = infoDict['axisOfRotation'] #sizes = infoDict['sizes'] params = n.array(params) finalSize = n.ceil(stacks[0].GetSize()).astype(n.int64) # finalSpacing = n.array(stacks[0].GetSpacing()).astype(n.float64) # tmpMatrix = n.zeros((4,4)).astype(n.float) # tmpMatrix[:3,:3] = params[1][:9].reshape((3,3)) # direction = transformations.rotation_from_matrix(tmpMatrix)[1] axisOfRotation = n.argmax(n.abs(params[1][[0,4,8]])) print 'determining axis of rotation from parameters... %s' %axisOfRotation axes = range(3) axes.remove(axisOfRotation) firstAxis = axes[0] lastAxis = axes[1] def calcAngles(Y,Z): norm = n.sqrt(n.power(Y,2)+n.power(Z,2)) norm[norm==0] = 0.001 angles = [] angles.append(n.arccos(Y/norm)) angles.append(2*n.pi-n.arccos(Y/norm)) #angles.append(n.pi-n.arccos(-Y/norm)) #angles.append(n.pi+n.arccos(-Y/norm)) finalAngles = n.zeros(Y.shape,dtype=n.float64) #criteria = [(Y>=0)*(Z>=0),(Y>=0)*(Z<0),(Y<0)*(Z>=0),(Y<0)*(Z<0)] criteria = [(Z>=0),(Z<0)] for icrit,crit in enumerate(criteria): finalAngles[crit] = angles[icrit][crit] return finalAngles if adaptiveCenterFile == None: centers = n.array([[finalSize[lastAxis],finalSize[firstAxis]]])/2. else: print 'calculating stack centers for fusion weights (assuming sample intensity of >%s)' %sampleIntensityThreshold #adaptiveCenterFileSpacing = n.array(adaptiveCenterFile.GetSpacing()) centers = [] Z, Y = n.mgrid[0:finalSize[lastAxis], 0:finalSize[firstAxis]] Z, Y = sitk.GetImageFromArray(Y.astype(n.uint16)), sitk.GetImageFromArray(Z.astype(n.uint16)) for x in range(adaptiveCenterFile.GetSize()[axisOfRotation]): if axisOfRotation == 0: xImage = adaptiveCenterFile[x] elif axisOfRotation == 1: xImage = adaptiveCenterFile[:,x] elif axisOfRotation == 2: xImage = adaptiveCenterFile[:,:,x] #pdb.set_trace() Z.SetOrigin(xImage.GetOrigin()) Z.SetSpacing(xImage.GetSpacing()) Y.SetOrigin(xImage.GetOrigin()) Y.SetSpacing(xImage.GetSpacing()) xImage = sitk.Cast(xImage>sampleIntensityThreshold,7)*1000+0.01 #careful, could create overflow totalIntensity = sitk.SumProjection(sitk.SumProjection(xImage,0),1).GetPixel(0,0) z = sitk.SumProjection(sitk.SumProjection(sitk.Cast(Z,7)*xImage,0),1).GetPixel(0,0)/totalIntensity y = sitk.SumProjection(sitk.SumProjection(sitk.Cast(Y,7)*xImage,0),1).GetPixel(0,0)/totalIntensity # totalIntensity = sitk.SumProjection(sitk.SumProjection(sitk.GetImageFromArray(n.ones(xImage.GetSize())),0),1).GetPixel(0,0) #pdb.set_trace() # z = sitk.SumProjection(sitk.SumProjection(Z,0),1).GetPixel(0,0)/totalIntensity # y = sitk.SumProjection(sitk.SumProjection(Y,0),1).GetPixel(0,0)/totalIntensity # tmp = sitk.GetArrayFromImage(xImage) # tmp[int(y),int(z)] = 2000 # plt.imshow(tmp) # plt.colorbar() # plt.show() center = [y,z] centers.append(center) # smoothen center line centers = n.array(centers) #centers = n.array([ndimage.gaussian_filter(centers[:,i],finalSize[[firstAxis,lastAxis][i]]/30.) for i in range(2)]) #centers = centers.swapaxes(0,1) # get angles refCenter = n.array(stacks[0].TransformIndexToPhysicalPoint([int(i) for i in n.array(stacks[0].GetSize())/2.])) #origCenter = n.array([refCenter[i] for i in [lastAxis,firstAxis]]) bestAngles = [] refPoints = [] print 'refCenter %s' %refCenter refPoints.append(refCenter) for iparam,param in enumerate(params): # point2 is refCenter in rotated view point2 = beads.transform(param,[refCenter])[0] # shift point2 in z (positive here since later compared to positive again) point2[lastAxis] += 100 # transform back to reference view refPoint = beads.backTransform(param,[point2])[0] refPoints.append(refPoint) # calc direction vector refVector = refPoint-refCenter refVector = n.array([refVector[i] for i in [lastAxis,firstAxis]]) refVector = refVector/n.linalg.norm(refVector) # calc angle with respect to [1,1] angle = calcAngles(n.array([refVector[0]]),n.array([refVector[1]])) bestAngles.append(angle) #pdb.set_trace() refPoints = n.array(refPoints) # plt.plot(refPoints[:,0],refPoints[:,2],'o') # plt.show() zCenter = finalSize[[lastAxis,firstAxis]]/2. lower = n.array([0,0]) upper = finalSize[[lastAxis,firstAxis]] templateLower = lower - n.max(centers,0)+zCenter templateUpper = upper - n.min(centers,0)+zCenter print templateLower,templateUpper deltaplus = n.ceil(templateUpper-zCenter) deltaminus = n.ceil(zCenter-templateLower) templateSize = deltaminus+deltaplus Y,Z = n.mgrid[0:templateSize[0],0:templateSize[1]] Y = Y-deltaminus[0] Z = Z-deltaminus[1] norm = n.sqrt(n.power(Y,2)+n.power(Z,2)) sigmoidHalfWidthInPixels = n.mean(finalSize[[firstAxis,lastAxis]])*sigmoidHalfWidthRelativeToImageSize halfY = 0.9 # half width is defined as the x value corresponding to y=halfY norm[norm==0] = 0.0001 sigmoidA = n.log(1./halfY-1.)/n.arctan(sigmoidHalfWidthInPixels/norm) finalAngles = calcAngles(Y,Z) # plt.imshow(finalAngles) # plt.title('finalAngles') # plt.colorbar() # plt.show() # add cameras here viewAngles = [] for i in range(len(bestAngles)): viewAngle = [] viewAngle.append(bestAngles[i]) viewAngle.append((bestAngles[i]+n.pi)%(2*n.pi)) viewAngles.append(viewAngle) print viewAngles # calculate difference to ref angles weights = [] for iview,viewAngle in enumerate(viewAngles): tmp = n.min([n.min([n.abs(finalAngles-i),n.abs(2*n.pi-n.abs(finalAngles-i))],0) for i in viewAngle],0) weights.append(tmp.astype(n.float32)) # plt.imshow(weights[iview]) # plt.title('weights1 %s' %iview) # plt.colorbar() # plt.show() # #tifffile.imsave('/home/malbert/delme/test%s.tif' %(iview),weights[iview]) weightsDiff = [] for iview,view in enumerate(viewAngles): weightsDiff.append(n.min([-weights[iview]+weights[i] for i in n.delete(range(len(viewAngles)),iview,0)],0)) #tifffile.imsave('/home/malbert/delme/test%s.tif' %(iview),weightsDiff[iview]) #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weightsDiff[iview]),3),'/home/malbert/delme/test%s.tif' %(iview)) # plt.imshow(weightsDiff[iview]) # plt.title('weightsDiff1 %s' %iview) # plt.colorbar() # plt.show() for iview,view in enumerate(viewAngles): weightsDiff[iview] = (1/(1+n.exp(sigmoidA*(weightsDiff[iview])))) # plt.imshow(weightsDiff[iview]) # plt.title('weightsDiff2 %s' %iview) # plt.colorbar() # plt.show() #pdb.set_trace() #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weightsDiff[iview]*100),3),'/home/malbert/delme/test%s.tif' %(iview)) weights = [] weightsDiffSum = n.sum(weightsDiff,0) for iview,view in enumerate(viewAngles): weights.append(weightsDiff[iview]/weightsDiffSum) #sitk.WriteImage(sitk.Cast(sitk.GetImageFromArray(weights[iview]*1000),3),'/home/malbert/delme/test%s.tif' %(iview)) #sitk.WriteImage(sitk.Cast(finalWeights[iview]*1000,3),'/home/malbert/delme/test0.tif') xWeights = [] for icenter, center in enumerate(centers): xWeight = [] for iview,view in enumerate(viewAngles): # pdb.set_trace() # plt.imshow(weights[iview]) # plt.title('test') # plt.colorbar() # plt.show() xW = sitk.GetImageFromArray(weights[iview]) #xW.SetOrigin((templateLower[0], templateLower[1])) xW.SetOrigin([0,0]) tmpTransform = sitk.Transform(2,1) tmpSize = finalSize[[lastAxis,firstAxis]].astype(n.int64) tmpSize = [int(i) for i in tmpSize[::-1]] tmpOrigin = n.array([-center[i]+deltaminus[i] for i in [1,0]]) #pdb.set_trace() tmpTransform.SetParameters(tmpOrigin) #pdb.set_trace() xW = sitk.Resample(xW, tmpSize, tmpTransform, sitk.sitkLinear, #tmpOrigin ) #pdb.set_trace() xW = sitk.GetArrayFromImage(xW) xWeight.append(xW) # plt.imshow(xW) # plt.title('weights %s %s' %(iview,center)) # plt.colorbar() # plt.show() xWeights.append(xWeight) finalWeights = [] for i in range(len(params)): #finalWeights.append(sitk.GetImageFromArray(xWeights[0][i])) if adaptiveCenterFile is None: tmp = n.array([xWeights[0][i]]*finalSize[axisOfRotation]) else: tmp = n.array([xWeights[j][i] for j in range(finalSize[axisOfRotation])]) if axisOfRotation == 0: numpyAxisOfRotation = 2 elif axisOfRotation == 1: numpyAxisOfRotation = 1 elif axisOfRotation == 2: numpyAxisOfRotation = 0 tmp = tmp.swapaxes(0,numpyAxisOfRotation) if numpyAxisOfRotation == 2: otherAxes = range(3) otherAxes.remove(numpyAxisOfRotation) tmp = tmp.swapaxes(otherAxes[0],otherAxes[1]) #tmp = tmp.swapaxes(0, 1).swapaxes(1, 2).astype(n.float32) tmp = tmp.astype(n.float32) finalWeights.append(sitk.GetImageFromArray(tmp)) #sitk.WriteImage(sitk.Cast(finalWeights[iview]*1000,3),'/home/malbert/delme/test.tif') return finalWeights