本文整理汇总了C#中Image.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Image.Dispose方法的具体用法?C# Image.Dispose怎么用?C# Image.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Image
的用法示例。
在下文中一共展示了Image.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: resizeImage
// Returns the thumbnail image when an image object is passed in
public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
try
{
// Prevent using images internal thumbnail
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
// Set new width if in bounds
if (onlyResizeIfWider)
{
if (ImageToResize.Width <= newWidth)
{
newWidth = ImageToResize.Width;
}
}
// Calculate new height
int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;
if (newHeight > maxHeight)
{
// Resize with height instead
newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;
newHeight = maxHeight;
}
// Create the new
if (newWidth > 120 || newHeight > 120)
{
Bitmap newImage = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newImage.SetResolution(ImageToResize.HorizontalResolution, ImageToResize.VerticalResolution);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(ImageToResize, new Rectangle(0, 0, newWidth, newHeight));
}
return newImage;
}
else
{
Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
return resizedImage;
}
}
catch
{
return null;
}
finally
{
// Clear handle to original file so that we can overwrite it if necessary
ImageToResize.Dispose();
}
}
示例2: Crop
public static Image Crop(Image image, Rectangle selection)
{
try
{
Bitmap bmp = image as Bitmap;
// Check if it is a bitmap:
if (bmp == null)
throw new ArgumentException("No valid bitmap");
// Crop the image:
Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat);
// Release the resources:
image.Dispose();
return cropBmp;
}
catch (Exception)
{
return image;
}
}
示例3: CreateInfoCardImage
private Image CreateInfoCardImage() {
// add clickable image
Image image = new Image();
try {
image.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(InfoCardSelector), InfoCardImage.GetImageManifestResourceStreamName(this.ImageSize));
image.AlternateText = InfoCardStrings.SelectorClickPrompt;
image.ToolTip = this.ToolTip;
image.Style[HtmlTextWriterStyle.Cursor] = "hand";
image.Attributes["onclick"] = this.GetInfoCardSelectorActivationScript(false);
return image;
} catch {
image.Dispose();
throw;
}
}
示例4: AddFrame
/// <summary>
/// Adds a frame to this animation.
/// </summary>
/// <param name="Image">The image to add</param>
/// <param name="XOffset">The positioning x offset this image should be displayed at.</param>
/// <param name="YOffset">The positioning y offset this image should be displayed at.</param>
public void AddFrame(Image Image, double? frameDelay = null, int XOffset = 0, int YOffset = 0)
{
using (var gifStream = new MemoryStream())
{
GifFrame Frame = new GifFrame(Image, frameDelay ?? DefaultFrameDelay, XOffset, YOffset);
Frame.Image.Save(gifStream, ImageFormat.Gif);
// Steal the global color table info
if (countOfFrame == 0) InitHeader(gifStream, Writer, Frame.Image.Width, Frame.Image.Height);
WriteGraphicControlBlock(gifStream, Writer, Frame.Delay);
WriteImageBlock(gifStream, Writer, countOfFrame != 0, Frame.XOffset, Frame.YOffset, Frame.Image.Width, Frame.Image.Height);
countOfFrame++;
}
Image.Dispose();
}
示例5: TextDisplay
/// <summary>
/// Constructs a text display.
/// </summary>
/// <param name="width">Width in characters</param>
/// <param name="height">Height in characters</param>
/// <param name="fontFile">Font texture</param>
/// <param name="convertFont">Enable support for masked fonts</param>
/// <param name="paletteFile">Palette texture</param>
public TextDisplay(uint width, uint height, string fontFile = "font.png", bool convertFont = true, string paletteFile = "palette.png")
{
if (string.IsNullOrEmpty(fontFile))
throw new ArgumentNullException("fontFile");
if (string.IsNullOrEmpty(paletteFile))
throw new ArgumentNullException("paletteFile");
Width = width;
Height = height;
_data = new Image(width, height, Color.Black);
_dataTexture = new Texture(_data);
var fontImage = new Image(Path.Combine(DataFolder, fontFile));
CharacterWidth = fontImage.Size.X / 16;
CharacterHeight = fontImage.Size.Y / 16;
if (convertFont)
{
var fontWidth = fontImage.Size.X;
var fontHeight = fontImage.Size.Y;
var fontPixels = fontImage.Pixels;
fontImage.Dispose();
// use top left pixel of space as mask color
var maskX = (32 % 16) * CharacterWidth;
var maskY = (32 / 16) * CharacterHeight * (fontWidth * 4);
var maskI = maskX + maskY;
var maskR = fontPixels[maskI + 0];
var maskG = fontPixels[maskI + 1];
var maskB = fontPixels[maskI + 2];
var maskA = fontPixels[maskI + 3];
for (int i = 0; i < fontPixels.Length; i += 4)
{
var r = fontPixels[i + 0];
var g = fontPixels[i + 1];
var b = fontPixels[i + 2];
var a = fontPixels[i + 3];
if (r == maskR && g == maskG && b == maskB && a == maskA)
{
// mask color, set to transparent
fontPixels[i + 3] = 0;
}
else
{
// set alpha channel to average of rgb
var level = (r + b + g) / 3f;
var alpha = a / 256f;
fontPixels[i + 3] = (byte)(level * alpha);
}
}
fontImage = new Image(fontWidth, fontHeight, fontPixels);
//fontImage.SaveToFile("result.png");
}
_fontTexture = new Texture(fontImage);
_palette = new Image(Path.Combine(DataFolder, paletteFile));
_paletteTexture = new Texture(_palette);
_display = new VertexArray(PrimitiveType.Quads, 4);
_display[0] = new Vertex(new Vector2f(0, 0), new Vector2f(0, 0));
_display[1] = new Vertex(new Vector2f(width * CharacterWidth, 0), new Vector2f(1, 0));
_display[2] = new Vertex(new Vector2f(width * CharacterWidth, height * CharacterHeight), new Vector2f(1, 1));
_display[3] = new Vertex(new Vector2f(0, height * CharacterHeight), new Vector2f(0, 1));
var displayVertexSource = File.ReadAllText(Path.Combine(DataFolder, "texter.vert"));
var displayFragmentSource = File.ReadAllText(Path.Combine(DataFolder, "texter.frag"))
.Replace("#W#", CharacterWidth.ToString("D"))
.Replace("#H#", CharacterHeight.ToString("D"));
_renderer = Shader.FromString(displayVertexSource, displayFragmentSource);
_renderer.SetParameter("data", _dataTexture);
_renderer.SetParameter("dataSize", width, height);
_renderer.SetParameter("font", _fontTexture);
_renderer.SetParameter("palette", _paletteTexture);
}
示例6: GenerateTabs
private void GenerateTabs()
{
VBox tab = new VBox();
Image img = new Image();
img.Pixbuf = Images.GetPixbuf("options-general.png");
tab.PackStart(img, false, false, 2);
tab.PackEnd(new Label("General"), false, false, 0);
tab.SetSizeRequest(60,50);
tab.ShowAll();
optionTabs.AppendPage(GenerateGeneral(), tab);
tab = new VBox();
img = new Image();
img.Pixbuf = Images.GetPixbuf("options-text-editors.png");
tab.PackStart(img, false, false, 2);
tab.PackEnd(new Label("Text Editors"), false, false, 0);
tab.SetSizeRequest(60,50);
tab.ShowAll();
optionTabs.AppendPage(GenerateTextEditors(), tab);
tab = new VBox();
img = new Image();
img.Pixbuf = Images.GetPixbuf("options-results.png");
tab.PackStart(img, false, false, 2);
tab.PackEnd(new Label("Results"), false, false, 0);
tab.SetSizeRequest(60,50);
tab.ShowAll();
optionTabs.AppendPage(GenerateResults(), tab);
tab = new VBox();
img = new Image();
img.Pixbuf = Images.GetPixbuf("options-plugins.png");
tab.PackStart(img, false, false, 2);
tab.PackEnd(new Label("Plugins"), false, false, 0);
tab.SetSizeRequest(60,50);
tab.ShowAll();
optionTabs.AppendPage(GeneratePlugins(), tab);
tab.Dispose();
img.Dispose();
optionTabs.SwitchPage += new SwitchPageHandler(optionTabs_SwitchPage);
}
示例7: ProcessParticleCTF
public void ProcessParticleCTF(MapHeader originalHeader, Image originalStack, Star stardata, Image refft, Image maskft, int dimbox, decimal scaleFactor)
{
//CTF.Cs = MainWindow.Options.CTFCs;
#region Dimensions and grids
int NFrames = originalHeader.Dimensions.Z;
int2 DimsImage = new int2(originalHeader.Dimensions);
int2 DimsRegion = new int2(dimbox, dimbox);
float3[] PositionsGrid;
float3[] PositionsExtraction;
float3[] ParticleAngles;
List<int> RowIndices = new List<int>();
{
string[] ColumnNames = stardata.GetColumn("rlnMicrographName");
for (int i = 0; i < ColumnNames.Length; i++)
if (ColumnNames[i].Contains(RootName))
RowIndices.Add(i);
string[] ColumnOriginX = stardata.GetColumn("rlnCoordinateX");
string[] ColumnOriginY = stardata.GetColumn("rlnCoordinateY");
string[] ColumnShiftX = stardata.GetColumn("rlnOriginX");
string[] ColumnShiftY = stardata.GetColumn("rlnOriginY");
string[] ColumnAngleRot = stardata.GetColumn("rlnAngleRot");
string[] ColumnAngleTilt = stardata.GetColumn("rlnAngleTilt");
string[] ColumnAnglePsi = stardata.GetColumn("rlnAnglePsi");
PositionsGrid = new float3[RowIndices.Count];
PositionsExtraction = new float3[RowIndices.Count];
ParticleAngles = new float3[RowIndices.Count];
{
int i = 0;
foreach (var nameIndex in RowIndices)
{
float OriginX = float.Parse(ColumnOriginX[nameIndex]);
float OriginY = float.Parse(ColumnOriginY[nameIndex]);
float ShiftX = float.Parse(ColumnShiftX[nameIndex]);
float ShiftY = float.Parse(ColumnShiftY[nameIndex]);
PositionsExtraction[i] = new float3(OriginX - ShiftX - dimbox / 2, OriginY - ShiftY - dimbox / 2, 0f);
PositionsGrid[i] = new float3((OriginX - ShiftX) / DimsImage.X, (OriginY - ShiftY) / DimsImage.Y, 0);
ParticleAngles[i] = new float3(float.Parse(ColumnAngleRot[nameIndex]) * Helper.ToRad,
float.Parse(ColumnAngleTilt[nameIndex]) * Helper.ToRad,
float.Parse(ColumnAnglePsi[nameIndex]) * Helper.ToRad);
i++;
}
}
}
int NPositions = PositionsGrid.Length;
if (NPositions == 0)
return;
int CTFGridX = MainWindow.Options.GridCTFX;
int CTFGridY = MainWindow.Options.GridCTFY;
int CTFGridZ = Math.Min(NFrames, MainWindow.Options.GridCTFZ);
int FrameGroupSize = CTFGridZ > 1 ? 12 : 1;
int NFrameGroups = CTFGridZ > 1 ? NFrames / FrameGroupSize : 1;
GridCTF = GridCTF.Resize(new int3(CTFGridX, CTFGridY, CTFGridZ));
GridCTFPhase = GridCTFPhase.Resize(new int3(1, 1, CTFGridZ));
int NSpectra = NFrameGroups * NPositions;
int MinFreqInclusive = (int)(MainWindow.Options.CTFRangeMin * DimsRegion.X / 2);
int MaxFreqExclusive = (int)(MainWindow.Options.CTFRangeMax * DimsRegion.X / 2);
int NFreq = MaxFreqExclusive - MinFreqInclusive;
float PixelSize = (float)CTF.PixelSize;
float PixelDelta = (float)CTF.PixelSizeDelta;
float PixelAngle = (float)CTF.PixelSizeAngle * Helper.ToRad;
#endregion
#region Allocate GPU memory
Image CTFSpectra = new Image(IntPtr.Zero, new int3(DimsRegion.X, DimsRegion.X, NSpectra), true, true);
Image CTFCoordsCart = new Image(new int3(DimsRegion), true, true);
Image ParticleRefs = refft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
/*Image ParticleRefsIFT = ParticleRefs.AsIFFT();
ParticleRefsIFT.WriteMRC("d_particlerefs.mrc");
ParticleRefsIFT.Dispose();*/
#endregion
// Extract movie regions, create individual spectra in Cartesian coordinates.
#region Create spectra
Image ParticleMasksFT = maskft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
Image ParticleMasks = ParticleMasksFT.AsIFFT();
ParticleMasksFT.Dispose();
Parallel.ForEach(ParticleMasks.GetHost(Intent.ReadWrite), slice =>
{
for (int i = 0; i < slice.Length; i++)
slice[i] = (Math.Max(2f, Math.Min(25f, slice[i])) - 2) / 23f;
});
//.........这里部分代码省略.........
示例8: createOverlay
// *******************
// SNS Added 04-24-14
// *******************
public void createOverlay(System.Drawing.Point[] myPoly, Image<Bgr, Byte> overlayImage)
{
System.Drawing.Point[] singlePoly = myPoly;
System.Drawing.PointF[] singlePolyF = Array.ConvertAll(singlePoly, item => (System.Drawing.PointF)item);
// System.Diagnostics.Debug.WriteLine(singlePolyF[0] + " " + singlePolyF[1] + " " + singlePolyF[2] + " " + singlePolyF[3]);
// Compute the transform matrix
// GetPerspectiveTransform wants PointF[] arrays
HomographyMatrix matrixM = CameraCalibration.GetPerspectiveTransform(overlayPoly, singlePolyF);
// then we need to overlay the transformation onto the original image
Image<Bgr, Byte> whiteOverlay = new Image<Bgr, Byte>(overlayImage.Size.Width, overlayImage.Size.Height, new Bgr(255, 255, 255));
Image<Bgr, Byte> mask = new Image<Bgr, Byte>(CVKinectColorFrame.Size.Width, CVKinectColorFrame.Size.Height, new Bgr(0,0,0));
// apply perspective transform to the white image to make a mask
mask = whiteOverlay.WarpPerspective(matrixM, CVKinectColorFrame.Size.Width, CVKinectColorFrame.Size.Height, Emgu.CV.CvEnum.INTER.CV_INTER_NN, Emgu.CV.CvEnum.WARP.CV_WARP_DEFAULT, new Bgr(0, 0, 0));
// System.Diagnostics.Debug.WriteLine("warp perspective done");
// mask.Save(@"C:\Users\wayne\Desktop\Mask.jpg");
// apply warpPerspective to the image we want to warp
Image<Bgr, Byte> correctedOverlay = overlayImage.WarpPerspective(matrixM, Emgu.CV.CvEnum.INTER.CV_INTER_NN, Emgu.CV.CvEnum.WARP.CV_WARP_DEFAULT, new Bgr(0,0,0));
// System.Diagnostics.Debug.WriteLine("warp perspective 2 done");
// correctedOverlay.Save(@"C:\Users\wayne\Desktop\Corrected.jpg");
// copy the correctd overlay onto the kinect image using the mask
correctedOverlay.Copy(CVKinectColorFrame, mask.Convert<Gray, Byte>());
// CVKinectColorFrame.Save(@"C:\Users\wayne\Desktop\frame.jpg");
mask.Dispose();
whiteOverlay.Dispose();
// correctedOverlay.Dispose();
// matrixM.Dispose();
// *************
// SNS - 04-14
// *************
}
示例9: ExportParticlesMovieOld
//.........这里部分代码省略.........
Weights.Fill(1e-6f);
Image FrameParticles = new Image(IntPtr.Zero, new int3(DimsRegion.X * 2, DimsRegion.Y * 2, NParticles));
float StepZ = 1f / Math.Max(Dims.Z - 1, 1);
for (int z = 0; z < Dims.Z; z++)
{
float CoordZ = z * StepZ;
/*GPU.Extract(OriginalStack.GetDeviceSlice(z, Intent.Read),
FrameParticles.GetDevice(Intent.Write),
Dims.Slice(),
new int3(DimsRegion.X * 2, DimsRegion.Y * 2, 1),
Helper.ToInterleaved(Origins),
(uint)NParticles);*/
// Shift particles
{
float3[] Shifts = new float3[NParticles];
for (int i = 0; i < NParticles; i++)
{
float NormX = Math.Max(0.15f, Math.Min((float)Origins[i].X / Dims.X, 0.85f));
float NormY = Math.Max(0.15f, Math.Min((float)Origins[i].Y / Dims.Y, 0.85f));
float3 Coords = new float3(NormX, NormY, CoordZ);
Shifts[i] = new float3(GridMovementX.GetInterpolated(Coords) + ParticleTracks[i][z].X,
GridMovementY.GetInterpolated(Coords) + ParticleTracks[i][z].Y,
0f);
}
FrameParticles.ShiftSlices(Shifts);
}
Image FrameParticlesCropped = FrameParticles.AsPadded(new int2(DimsRegion));
Image FrameParticlesFT = FrameParticlesCropped.AsFFT();
FrameParticlesCropped.Dispose();
Image PS = new Image(new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
PS.Fill(1f);
// Apply motion blur filter.
{
const int Samples = 11;
float StartZ = (z - 0.75f) * StepZ;
float StopZ = (z + 0.75f) * StepZ;
float2[] Shifts = new float2[Samples * NParticles];
for (int p = 0; p < NParticles; p++)
{
float NormX = Math.Max(0.15f, Math.Min((float)Origins[p].X / Dims.X, 0.85f));
float NormY = Math.Max(0.15f, Math.Min((float)Origins[p].Y / Dims.Y, 0.85f));
for (int zz = 0; zz < Samples; zz++)
{
float zp = StartZ + (StopZ - StartZ) / (Samples - 1) * zz;
float3 Coords = new float3(NormX, NormY, zp);
Shifts[p * Samples + zz] = new float2(GridMovementX.GetInterpolated(Coords),
GridMovementY.GetInterpolated(Coords));
}
}
Image MotionFilter = new Image(IntPtr.Zero, new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
GPU.CreateMotionBlur(MotionFilter.GetDevice(Intent.Write),
DimsRegion,
Helper.ToInterleaved(Shifts.Select(v => new float3(v.X, v.Y, 0)).ToArray()),
Samples,
(uint)NParticles);
PS.Multiply(MotionFilter);
示例10: ExportParticlesMovie
//.........这里部分代码省略.........
{
float CoordZ = z * StepZ;
#region Extract, correct, and norm particles
#region Half 1
{
if (originalStack != null)
GPU.Extract(originalStack.GetDeviceSlice(z, Intent.Read),
FrameParticles1.GetDevice(Intent.Write),
Dims.Slice(),
DimsPadded,
Helper.ToInterleaved(Origins1.Select(v => new int3(v.X - DimsPadded.X / 2, v.Y - DimsPadded.Y / 2, 0)).ToArray()),
(uint)NParticles1);
// Shift particles
{
float3[] Shifts = new float3[NParticles1];
for (int i = 0; i < NParticles1; i++)
{
float3 Coords = new float3((float)Origins1[i].X / Dims.X, (float)Origins1[i].Y / Dims.Y, CoordZ);
Shifts[i] = ResidualShifts1[i] + new float3(GetShiftFromPyramid(Coords)) * 1.00f;
}
FrameParticles1.ShiftSlices(Shifts);
}
Image FrameParticlesCropped = FrameParticles1.AsPadded(new int2(DimsRegion));
Image FrameParticlesCorrected = FrameParticlesCropped.AsAnisotropyCorrected(new int2(DimsRegion),
PixelSize + PixelDelta / 2f,
PixelSize - PixelDelta / 2f,
PixelAngle,
6);
FrameParticlesCropped.Dispose();
GPU.NormParticles(FrameParticlesCorrected.GetDevice(Intent.Read),
FrameParticlesCorrected.GetDevice(Intent.Write),
DimsRegion,
(uint)(particleradius / PixelSize),
true,
(uint)NParticles1);
float[][] FrameParticlesCorrectedData = FrameParticlesCorrected.GetHost(Intent.Read);
for (int n = 0; n < NParticles1; n++)
{
ParticleStackData[z * NParticles + n] = FrameParticlesCorrectedData[n];
ParticleStackData1[z * NParticles1 + n] = FrameParticlesCorrectedData[n];
}
//FrameParticlesCorrected.WriteMRC("intermediate_particles1.mrc");
FrameParticlesCorrected.Dispose();
}
#endregion
#region Half 2
{
if (originalStack != null)
GPU.Extract(originalStack.GetDeviceSlice(z, Intent.Read),
FrameParticles2.GetDevice(Intent.Write),
Dims.Slice(),
DimsPadded,
Helper.ToInterleaved(Origins2.Select(v => new int3(v.X - DimsPadded.X / 2, v.Y - DimsPadded.Y / 2, 0)).ToArray()),
(uint)NParticles2);
// Shift particles
示例11: ExportParticles
//.........这里部分代码省略.........
Image AverageFT = new Image(new int3(DimsRegion.X, DimsRegion.Y, NParticles), true, true);
Image AveragePS = new Image(new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
Image Weights = new Image(new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
Weights.Fill(1e-6f);
Image FrameParticles = new Image(IntPtr.Zero, new int3(DimsPadded.X, DimsPadded.Y, NParticles));
float StepZ = 1f / Math.Max(Dims.Z - 1, 1);
for (int z = 0; z < Dims.Z; z++)
{
float CoordZ = z * StepZ;
if (originalStack != null)
GPU.Extract(originalStack.GetDeviceSlice(z, Intent.Read),
FrameParticles.GetDevice(Intent.Write),
Dims.Slice(),
DimsPadded,
Helper.ToInterleaved(Origins.Select(v => new int3(v.X - DimsPadded.X / 2, v.Y - DimsPadded.Y / 2, 0)).ToArray()),
(uint)NParticles);
// Shift particles
{
float3[] Shifts = new float3[NParticles];
for (int i = 0; i < NParticles; i++)
{
float3 Coords = new float3((float)Origins[i].X / Dims.X, (float)Origins[i].Y / Dims.Y, CoordZ);
Shifts[i] = ResidualShifts[i] + new float3(GetShiftFromPyramid(Coords)) * 1.00f;
}
FrameParticles.ShiftSlices(Shifts);
}
Image FrameParticlesCropped = FrameParticles.AsPadded(new int2(DimsRegion));
Image FrameParticlesFT = FrameParticlesCropped.AsFFT();
FrameParticlesCropped.Dispose();
//Image PS = new Image(new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
//PS.Fill(1f);
// Apply motion blur filter.
#region Motion blur weighting
/*{
const int Samples = 11;
float StartZ = (z - 0.5f) * StepZ;
float StopZ = (z + 0.5f) * StepZ;
float2[] Shifts = new float2[Samples * NParticles];
for (int p = 0; p < NParticles; p++)
{
float NormX = (float)Origins[p].X / Dims.X;
float NormY = (float)Origins[p].Y / Dims.Y;
for (int zz = 0; zz < Samples; zz++)
{
float zp = StartZ + (StopZ - StartZ) / (Samples - 1) * zz;
float3 Coords = new float3(NormX, NormY, zp);
Shifts[p * Samples + zz] = GetShiftFromPyramid(Coords);
}
}
Image MotionFilter = new Image(IntPtr.Zero, new int3(DimsRegion.X, DimsRegion.Y, NParticles), true);
GPU.CreateMotionBlur(MotionFilter.GetDevice(Intent.Write),
DimsRegion,
Helper.ToInterleaved(Shifts.Select(v => new float3(v.X, v.Y, 0)).ToArray()),
Samples,
示例12: CreateCorrected
public void CreateCorrected(MapHeader originalHeader, Image originalStack)
{
if (!Directory.Exists(AverageDir))
Directory.CreateDirectory(AverageDir);
if (!Directory.Exists(CTFDir))
Directory.CreateDirectory(CTFDir);
if (MainWindow.Options.PostStack && !Directory.Exists(ShiftedStackDir))
Directory.CreateDirectory(ShiftedStackDir);
int3 Dims = originalStack.Dims;
Image ShiftedStack = null;
if (MainWindow.Options.PostStack)
ShiftedStack = new Image(Dims);
float PixelSize = (float)(MainWindow.Options.CTFPixelMin + MainWindow.Options.CTFPixelMax) * 0.5f;
float PixelDelta = (float)(MainWindow.Options.CTFPixelMax - MainWindow.Options.CTFPixelMin) * 0.5f;
float PixelAngle = (float)MainWindow.Options.CTFPixelAngle / (float)(180.0 / Math.PI);
Image CTFCoords;
{
float2[] CTFCoordsData = new float2[Dims.ElementsSlice()];
Helper.ForEachElementFT(new int2(Dims), (x, y, xx, yy) =>
{
float xs = xx / (float)Dims.X;
float ys = yy / (float)Dims.Y;
float r = (float)Math.Sqrt(xs * xs + ys * ys);
float angle = (float)(Math.Atan2(yy, xx) + Math.PI / 2.0);
float CurrentPixelSize = PixelSize + PixelDelta * (float)Math.Cos(2f * (angle - PixelAngle));
CTFCoordsData[y * (Dims.X / 2 + 1) + x] = new float2(r / CurrentPixelSize, angle);
});
CTFCoords = new Image(CTFCoordsData, Dims.Slice(), true);
CTFCoords.RemapToFT();
}
Image CTFFreq = CTFCoords.AsReal();
CubicGrid CollapsedMovementX = GridMovementX.CollapseXY();
CubicGrid CollapsedMovementY = GridMovementY.CollapseXY();
CubicGrid CollapsedCTF = GridCTF.CollapseXY();
Image AverageFT = new Image(Dims.Slice(), true, true);
Image AveragePS = new Image(Dims.Slice(), true, false);
Image Weights = new Image(Dims.Slice(), true, false);
Weights.Fill(1e-6f);
float StepZ = 1f / Math.Max(Dims.Z - 1, 1);
for (int nframe = 0; nframe < Dims.Z; nframe++)
{
Image PS = new Image(Dims.Slice(), true);
PS.Fill(1f);
// Apply motion blur filter.
/*{
float StartZ = (nframe - 0.5f) * StepZ;
float StopZ = (nframe + 0.5f) * StepZ;
float2[] Shifts = new float2[21];
for (int z = 0; z < Shifts.Length; z++)
{
float zp = StartZ + (StopZ - StartZ) / (Shifts.Length - 1) * z;
Shifts[z] = new float2(CollapsedMovementX.GetInterpolated(new float3(0.5f, 0.5f, zp)),
CollapsedMovementY.GetInterpolated(new float3(0.5f, 0.5f, zp)));
}
// Center the shifts around 0
float2 ShiftMean = MathHelper.Mean(Shifts);
Shifts = Shifts.Select(v => v - ShiftMean).ToArray();
Image MotionFilter = new Image(IntPtr.Zero, Dims.Slice(), true);
GPU.CreateMotionBlur(MotionFilter.GetDevice(Intent.Write),
MotionFilter.Dims,
Helper.ToInterleaved(Shifts.Select(v => new float3(v.X, v.Y, 0)).ToArray()),
(uint)Shifts.Length,
1);
PS.Multiply(MotionFilter);
//MotionFilter.WriteMRC("motion.mrc");
MotionFilter.Dispose();
}*/
// Apply CTF.
/*if (CTF != null)
{
CTF Altered = CTF.GetCopy();
Altered.Defocus = (decimal)CollapsedCTF.GetInterpolated(new float3(0.5f, 0.5f, nframe * StepZ));
Image CTFImage = new Image(IntPtr.Zero, Dims.Slice(), true);
GPU.CreateCTF(CTFImage.GetDevice(Intent.Write),
CTFCoords.GetDevice(Intent.Read),
(uint)CTFCoords.ElementsSliceComplex,
new[] { Altered.ToStruct() },
false,
1);
CTFImage.Abs();
PS.Multiply(CTFImage);
//CTFImage.WriteMRC("ctf.mrc");
CTFImage.Dispose();
}*/
//.........这里部分代码省略.........
示例13: ProcessParticleShift
//.........这里部分代码省略.........
CTF Altered = CTF.GetCopy();
Altered.PixelSizeDelta = 0;
Altered.Defocus = (decimal)v;
//Altered.Bfactor = -MainWindow.Options.MovementBfactor;
return Altered.ToStruct();
}).ToArray();
// Sort everyone with ascending distance from center.
List<KeyValuePair<float, int>> FreqIndices = Freq.Select((v, i) => new KeyValuePair<float, int>(v.X, i)).ToList();
FreqIndices.Sort((a, b) => a.Key.CompareTo(b.Key));
int[] SortedIndices = FreqIndices.Select(v => v.Value).ToArray();
Helper.Reorder(Positions, SortedIndices);
Helper.Reorder(Factors, SortedIndices);
Helper.Reorder(Freq, SortedIndices);
long[] RelevantMask = Positions.ToArray();
ShiftFactors = new Image(Helper.ToInterleaved(Factors.ToArray()));
MaskLength = RelevantMask.Length;
// Get mask sizes for different expansion steps.
for (int i = 0; i < MaskExpansions; i++)
{
float CurrentMaxFreq = MinFreqInclusive + (MaxFreqExclusive - MinFreqInclusive) / (float)MaskExpansions * (i + 1);
MaskSizes[i] = Freq.Count(v => v.X * v.X < CurrentMaxFreq * CurrentMaxFreq);
}
Phases = new Image(IntPtr.Zero, new int3(MaskLength, NPositions, NFrames), false, true, false);
Projections = new Image(IntPtr.Zero, new int3(MaskLength, NPositions, NFrames), false, true, false);
InvSigma = new Image(IntPtr.Zero, new int3(MaskLength, 1, 1));
Image ParticleMasksFT = maskft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
Image ParticleMasks = ParticleMasksFT.AsIFFT();
ParticleMasksFT.Dispose();
ParticleMasks.RemapFromFT();
Parallel.ForEach(ParticleMasks.GetHost(Intent.ReadWrite), slice =>
{
for (int i = 0; i < slice.Length; i++)
slice[i] = (Math.Max(2f, Math.Min(25f, slice[i])) - 2) / 23f;
});
Image ProjectionsSparse = refft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
Image InvSigmaSparse = new Image(new int3(DimsRegion), true);
{
int GroupNumber = int.Parse(stardata.GetRowValue(RowIndices[0], "rlnGroupNumber"));
//Star SigmaTable = new Star("D:\\rado27\\RefineWarppolish\\run1_model.star", "data_model_group_" + GroupNumber);
Star SigmaTable = new Star(MainWindow.Options.ModelStarPath, "data_model_group_" + GroupNumber);
float[] SigmaValues = SigmaTable.GetColumn("rlnSigma2Noise").Select(v => float.Parse(v)).ToArray();
float[] Sigma2NoiseData = InvSigmaSparse.GetHost(Intent.Write)[0];
Helper.ForEachElementFT(new int2(DimsRegion.X, DimsRegion.Y), (x, y, xx, yy, r, angle) =>
{
int ir = (int)r;
float val = 0;
if (ir < SigmaValues.Length)
{
if (SigmaValues[ir] != 0f)
val = 1f / SigmaValues[ir];
}
Sigma2NoiseData[y * (DimsRegion.X / 2 + 1) + x] = val;
});
float MaxSigma = MathHelper.Max(Sigma2NoiseData);
for (int i = 0; i < Sigma2NoiseData.Length; i++)
Sigma2NoiseData[i] /= MaxSigma;
示例14: ProcessShift
//.........这里部分代码省略.........
Helper.Reorder(Positions, SortedIndices);
Helper.Reorder(Factors, SortedIndices);
Helper.Reorder(Freq, SortedIndices);
float Bfac = (float)MainWindow.Options.MovementBfactor * 0.25f / PixelSize / DimsRegion.X;
float2[] BfacWeightsData = Freq.Select(v => (float)Math.Exp(v.X * Bfac)).Select(v => new float2(v, v)).ToArray();
Image BfacWeights = new Image(Helper.ToInterleaved(BfacWeightsData), false, false, false);
long[] RelevantMask = Positions.ToArray();
ShiftFactors = new Image(Helper.ToInterleaved(Factors.ToArray()));
MaskLength = RelevantMask.Length;
// Get mask sizes for different expansion steps.
for (int i = 0; i < MaskExpansions; i++)
{
float CurrentMaxFreq = MinFreqInclusive + (MaxFreqExclusive - MinFreqInclusive) / (float)MaskExpansions * (i + 1);
MaskSizes[i] = Freq.Count(v => v.X * v.X < CurrentMaxFreq * CurrentMaxFreq);
}
Phases = new Image(IntPtr.Zero, new int3(MaskLength * 2, DimsPositionGrid.X * DimsPositionGrid.Y, NFrames), false, false, false);
GPU.CreateShift(originalStack.GetDevice(Intent.Read),
new int2(originalHeader.Dimensions),
originalHeader.Dimensions.Z,
PositionGrid,
PositionGrid.Length,
DimsRegion,
RelevantMask,
(uint)MaskLength,
Phases.GetDevice(Intent.Write));
Phases.MultiplyLines(BfacWeights);
BfacWeights.Dispose();
originalStack.FreeDevice();
PhasesAverage = new Image(IntPtr.Zero, new int3(MaskLength, NPositions, 1), false, true, false);
Shifts = new Image(new float[NPositions * NFrames * 2]);
}
#region Fit global movement
{
int MinXSteps = 1, MinYSteps = 1;
int MinZSteps = Math.Min(NFrames, 3);
int3 ExpansionGridSize = new int3(MinXSteps, MinYSteps, MinZSteps);
float[][] WiggleWeights = new CubicGrid(ExpansionGridSize).GetWiggleWeights(ShiftGrid, new float3(DimsRegion.X / 2f / DimsImage.X, DimsRegion.Y / 2f / DimsImage.Y, 0f));
double[] StartParams = new double[ExpansionGridSize.Elements() * 2];
for (int m = 0; m < MaskExpansions; m++)
{
double[] LastAverage = null;
Action<double[]> SetPositions = input =>
{
// Construct CubicGrids and get interpolated shift values.
CubicGrid AlteredGridX = new CubicGrid(ExpansionGridSize, input.Where((v, i) => i % 2 == 0).Select(v => (float)v).ToArray());
float[] AlteredX = AlteredGridX.GetInterpolatedNative(new int3(DimsPositionGrid.X, DimsPositionGrid.Y, NFrames),
new float3(DimsRegion.X / 2f / DimsImage.X, DimsRegion.Y / 2f / DimsImage.Y, 0f));
CubicGrid AlteredGridY = new CubicGrid(ExpansionGridSize, input.Where((v, i) => i % 2 == 1).Select(v => (float)v).ToArray());
float[] AlteredY = AlteredGridY.GetInterpolatedNative(new int3(DimsPositionGrid.X, DimsPositionGrid.Y, NFrames),
new float3(DimsRegion.X / 2f / DimsImage.X, DimsRegion.Y / 2f / DimsImage.Y, 0f));
// Let movement start at 0 in the central frame.
/*float2[] CenterFrameOffsets = new float2[NPositions];
for (int i = 0; i < NPositions; i++)
示例15: PerformComparison
public void PerformComparison(MapHeader originalHeader, Star stardata, Image refft, Image maskft, decimal scaleFactor)
{
int NFrames = originalHeader.Dimensions.Z;
int2 DimsImage = new int2(originalHeader.Dimensions);
float3[] PositionsGrid;
float3[] PositionsShift;
float3[] ParticleAngles;
List<int> RowIndices = new List<int>();
{
string[] ColumnNames = stardata.GetColumn("rlnMicrographName");
for (int i = 0; i < ColumnNames.Length; i++)
if (ColumnNames[i].Contains(RootName))
RowIndices.Add(i);
string[] ColumnOriginX = stardata.GetColumn("rlnCoordinateX");
string[] ColumnOriginY = stardata.GetColumn("rlnCoordinateY");
string[] ColumnShiftX = stardata.GetColumn("rlnOriginX");
string[] ColumnShiftY = stardata.GetColumn("rlnOriginY");
string[] ColumnAngleRot = stardata.GetColumn("rlnAngleRot");
string[] ColumnAngleTilt = stardata.GetColumn("rlnAngleTilt");
string[] ColumnAnglePsi = stardata.GetColumn("rlnAnglePsi");
PositionsGrid = new float3[RowIndices.Count];
PositionsShift = new float3[RowIndices.Count];
ParticleAngles = new float3[RowIndices.Count];
{
int i = 0;
foreach (var nameIndex in RowIndices)
{
float OriginX = float.Parse(ColumnOriginX[nameIndex]);
float OriginY = float.Parse(ColumnOriginY[nameIndex]);
float ShiftX = float.Parse(ColumnShiftX[nameIndex]);
float ShiftY = float.Parse(ColumnShiftY[nameIndex]);
PositionsGrid[i] = new float3((OriginX - ShiftX) / DimsImage.X, (OriginY - ShiftY) / DimsImage.Y, 0);
PositionsShift[i] = new float3(ShiftX, ShiftY, 0f);
ParticleAngles[i] = new float3(-float.Parse(ColumnAngleRot[nameIndex]) * Helper.ToRad,
-float.Parse(ColumnAngleTilt[nameIndex]) * Helper.ToRad,
-float.Parse(ColumnAnglePsi[nameIndex]) * Helper.ToRad);
i++;
}
}
}
int NPositions = PositionsGrid.Length;
if (NPositions == 0)
return;
Image Particles = StageDataLoad.LoadMap(ParticlesPath, new int2(1, 1), 0, typeof (float));
int2 DimsRegion = new int2(Particles.Dims.X, Particles.Dims.X);
Particles.ShiftSlices(PositionsShift);
int MinFreqInclusive = (int)(MainWindow.Options.MovementRangeMin * DimsRegion.X / 2);
int MaxFreqExclusive = (int)(MainWindow.Options.MovementRangeMax * DimsRegion.X / 2);
int NFreq = MaxFreqExclusive - MinFreqInclusive;
Image ParticleMasksFT = maskft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
Image ParticleMasks = ParticleMasksFT.AsIFFT();
ParticleMasksFT.Dispose();
ParticleMasks.RemapFromFT();
Parallel.ForEach(ParticleMasks.GetHost(Intent.ReadWrite), slice =>
{
for (int i = 0; i < slice.Length; i++)
slice[i] = (Math.Max(2f, Math.Min(25f, slice[i])) - 2) / 23f;
});
Image ProjectionsFT = refft.AsProjections(ParticleAngles, DimsRegion, MainWindow.Options.ProjectionOversample);
Image Projections = ProjectionsFT.AsIFFT();
ProjectionsFT.Dispose();
// Addresses for CTF simulation
Image CTFCoordsCart = new Image(new int3(DimsRegion), true, true);
{
float2[] CoordsData = new float2[CTFCoordsCart.ElementsSliceComplex];
Helper.ForEachElementFT(DimsRegion, (x, y, xx, yy, r, a) => CoordsData[y * (DimsRegion.X / 2 + 1) + x] = new float2(r / DimsRegion.X, a));
CTFCoordsCart.UpdateHostWithComplex(new[] { CoordsData });
CTFCoordsCart.RemapToFT();
}
float[] ValuesDefocus = GridCTF.GetInterpolatedNative(PositionsGrid);
CTFStruct[] PositionsCTF = ValuesDefocus.Select(v =>
{
CTF Altered = CTF.GetCopy();
Altered.Defocus = (decimal)v;
//Altered.Bfactor = -MainWindow.Options.MovementBfactor;
return Altered.ToStruct();
}).ToArray();
Image Scores = new Image(IntPtr.Zero, new int3(NPositions, 1, 1));
GPU.CompareParticles(Particles.GetDevice(Intent.Read),
ParticleMasks.GetDevice(Intent.Read),
Projections.GetDevice(Intent.Read),
DimsRegion,
CTFCoordsCart.GetDevice(Intent.Read),
PositionsCTF,
//.........这里部分代码省略.........