use vtkUnsignedCharArray import byte[] - c#

I don't understand why a column of pixels on the right is moved to the left, and there is also a problem with the imported colors
This is My code
private void RendervtkImageImportBmp2()
{
var myBitMap = new Bitmap(bmpPath);
byte[] bmpBytes = BmpHelper.BitmapToByte(myBitMap);
GCHandle hObject = GCHandle.Alloc(bmpBytes, GCHandleType.Pinned);
var bmpInptr = hObject.AddrOfPinnedObject();
vtkImageImport imageImport = new vtkImageImport();
imageImport.SetDataSpacing(1, 1, 0);
imageImport.SetDataOrigin(0, 0, 0);
imageImport.SetWholeExtent(0, MyBitMap.Width - 1, 0, MyBitMap.Height - 1, 0, 0);
imageImport.SetDataExtentToWholeExtent();
imageImport.SetDataScalarTypeToUnsignedChar();
imageImport.SetNumberOfScalarComponents(3);
imageImport.SetImportVoidPointer(bmpInptr);
imageImport.Update();
var actor = new vtkImageActor();
actor.SetInput(imageImport.GetOutput());
var ren = new vtkRenderer();
ren.AddActor(actor);
var renWin = new vtkRenderWindow();
renWin.SetParentId(this.Handle);
renWin.SetSize((this.Width - (this.Width / 2)), this.Height);
renWin.SetPosition(0, 0);
renWin.AddRenderer(ren);
renWin.Render();
}
pictures show the result
this is afterimport picture
this is original image
I'm just getting started with VTK, please help me to see where I made a mistake, thank you

Related

'using' Statement being ignored

With the function below, I'm running into problems trying to access the WriteableBitmap.PixelBuffer property. The message I am getting is:
'WriteableBitmap' does not contain a definition for 'PixelBuffer' and no extension method 'PixelBuffer' accepting a first argument of type 'WriteableBitmap' could be found (are you missing a using directive or an assembly reference?)
I have read other places that I need to include
using System.Runtime.InteropServices.WindowsRuntime;
But when I use this include, nothing changes in my code. Looking through the references of my solution, I don't see anything like System.Runtime.InteropServices. Im frustrated as this seems to be the solution to other people trying to access the PixelBuffer of a WriteableBitmap.
private WriteableBitmap ChangeBrightness(WriteableBitmap source, byte change_value)
{
WriteableBitmap dest = new WriteableBitmap(source);
byte[] color = new byte[4];
using (Stream s = source.PixelBuffer.AsStream())
{
using (Stream d = dest.PixelBuffer.AsStream())
{
// read the pixel color
while (s.Read(color, 0, 4) > 0)
{
// color[0] = b
// color[1] = g
// color[2] = r
// color[3] = a
// do the adding algo per byte (skip the alpha)
for (int i = 0; i < 4; i++)
{
if ((int)color[i] + change_value > 255) color[i] = 255; else color[i] = (byte)(color[i] + change_value);
}
// write the new pixel color
d.Write(color, 0, 4);
}
}
}
// return the new bitmap
return dest;
}
Make sure you are referencing the assembly that package belongs to:
System.Runtime.WindowsRuntime assembly
I've ended up going about solving my original problem via other means. To adjust the brightness of my image, I ended up using this functions instead:
public ImageSource AdjustBrightness(BitmapImage Image, int Value, int mod)
{
Bitmap TempBitmap = BitmapImage2Bitmap(Image);
Bitmap NewBitmap = new Bitmap(TempBitmap.Width, TempBitmap.Height);
Graphics NewGraphics = Graphics.FromImage(NewBitmap);
float FinalValue = (float)Value / 255.0f;
float[][] FloatColorMatrix ={
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {mod * FinalValue, mod * FinalValue, mod * FinalValue, 1, 1}
};
ColorMatrix NewColorMatrix = new ColorMatrix(FloatColorMatrix);
ImageAttributes Attributes = new ImageAttributes();
Attributes.SetColorMatrix(NewColorMatrix);
NewGraphics.DrawImage(TempBitmap, new Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, GraphicsUnit.Pixel, Attributes);
Attributes.Dispose();
NewGraphics.Dispose();
return Bitmap2BitmapImage(NewBitmap);
}

I need recognize text in image using opencvsharp

I trying to identify text in an image.
Actually I'm trying to identify the text positions in the image then convert it to text.
I found a some code written on c++ and I am trying to convert it to c#.
Can you help me please?
Extracting text OpenCV
std::vector<cv::Rect> detectLetters(cv::Mat img)
{ std::vector<cv::Rect> boundRect;[enter image description here][1]
cv::Mat img_gray, img_sobel, img_threshold, element;
cvtColor(img, img_gray, CV_BGR2GRAY);
cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
cv::threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);
element = getStructuringElement(cv::MORPH_RECT, cv::Size(10, 15) );
cv::morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
std::vector< std::vector< cv::Point> > contours;
cv::findContours(img_threshold, contours, 0, 1);
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
for( int i = 0; i < contours.size(); i++ )
if (contours[i].size()>80)
{
cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 17, true );
cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
if (appRect.width>appRect.height)
boundRect.push_back(appRect);
}
return boundRect;
}
and i try to convert it to c#, but it didn't work
private List<Rectangle> detectLetters(IntPtr img)
{
//cvtColor(img, img_gray, CV_BGR2GRAY);
List<Rectangle> boundRect = new List<Rectangle>();
//cv::Mat img_gray, img_sobel, img_threshold, element;
IntPtr
img_gray = IntPtr.Zero,
img_sobel= IntPtr.Zero,
img_threshold= IntPtr.Zero,
img_tmp = IntPtr.Zero,
element= IntPtr.Zero;
//cvtColor(img, img_gray, CV_BGR2GRAY);
CvInvoke.cvCvtColor(img, img_gray,COLOR_CONVERSION.CV_BGR2GRAY); //CV_BGR2GRAY);
//cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
CvInvoke.cvSobel(img_gray, img_sobel, 0, 1, 1);//, 3, 1, 0, cv.BORDER_DEFAULT);
//cv.threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
CvInvoke.cvThreshold(img_sobel, img_threshold, 0, 255, THRESH.CV_THRESH_BINARY|THRESH.CV_THRESH_OTSU);
//element = getStructuringElement(cv.MORPH_RECT, cv.Size(10, 15));
element = CvInvoke.cvCreateStructuringElementEx(1,1,10,15,CV_ELEMENT_SHAPE.CV_SHAPE_RECT,element);// GetStructuringElement(
//cv.morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
CvInvoke.cvMorphologyEx(img_threshold,img_threshold,img_tmp,element,CV_MORPH_OP.CV_MOP_CLOSE,1);
//List<List<cv.Point>> contours = new List<List<cv.Point>>();
var contours = new List<IntPtr>();
//cv.findContours(img_threshold, contours, 0, 1);
CvInvoke.cvFindContours(img_threshold, element,ref ((IntPtr)contours[0]), 1, RETR_TYPE.CV_RETR_EXTERNAL, CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE,new Point(0,0));
//std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
var contours_poly = new List<List<Point>>(contours.Count);
//for( int i = 0; i < contours.size(); i++ )
for (int i = 0; i < contours.Count; i++)
{
//if (contours[i].size()>80)
if (contours[i].ToInt32() > 80)
{
//cv.approxPolyDP(Emgu.CV.Matrix<>(contours[i]), contours_poly[i], 17, true);
CvInvoke.cvApproxPoly(contours[i], 17,contours_poly[i],APPROX_POLY_TYPE.CV_POLY_APPROX_DP, 1,1);
//cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
Rectangle appRect = new Rectangle(CvInvoke.cvBoundingRect(contours_poly[i],false));
//if (appRect.width>appRect.height)
if (appRect.width > appRect.height)
{
//boundRect.push_back(appRect);
boundRect.Add(appRect);
}
}
}
//return boundRect;
return boundRect;
}
Depending on what the size of the text you're looking for, you may have to play around with the variables for element size and ApproxPolyDP but this code is pretty close to the original but in OpenCvSharp lingo.
static List<Rect> RunTextRecog(string inFile)
{
List<Rect> boundRect = new List<Rect>();
using (Mat img = new Mat(inFile))
using (Mat img_gray = new Mat())
using (Mat img_sobel = new Mat())
using (Mat img_threshold = new Mat())
{
Cv2.CvtColor(img, img_gray, ColorConversionCodes.BGR2GRAY);
Cv2.Sobel(img_gray, img_sobel, MatType.CV_8U, 1, 0, 3, 1, 0, BorderTypes.Default);
Cv2.Threshold(img_sobel, img_threshold, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
using (Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(10, 15)))
{
Cv2.MorphologyEx(img_threshold, img_threshold, MorphTypes.Close, element);
Point[][] edgesArray = img_threshold.Clone().FindContoursAsArray(RetrievalModes.External, ContourApproximationModes.ApproxNone);
foreach (Point[] edges in edgesArray)
{
Point[] normalizedEdges = Cv2.ApproxPolyDP(edges, 17, true);
Rect appRect = Cv2.BoundingRect(normalizedEdges);
boundRect.Add(appRect);
}
}
}
return boundRect;
}

Inverting image returns a black image

I want to invert an Image object. Currently my code looks like this:
private Image Invert(Image img)
{
var bmpPicture = new Bitmap(img.Width, img.Height);
var iaPicture = new ImageAttributes();
var cmPicture = new ColorMatrix { Matrix00 = -1, Matrix11 = -1, Matrix22 = -1 };
iaPicture.SetColorMatrix(cmPicture);
var gfxPicture = Graphics.FromImage(img);
var rctPicture = new Rectangle(0, 0, img.Width, img.Height);
gfxPicture.DrawImage(img, rctPicture, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, iaPicture);
return bmpPicture;
}
However, when I run this, and show it in a PictureBox, the result is a black image. I'm running this in Visual Studio 2012 under Windows 8 Release preview. If there is a better way to do this, please let me know. Thanks.
Try this: http://mariusbancila.ro/blog/2009/11/13/using-colormatrix-for-creating-negative-image/
public Bitmap Transform(Bitmap source)
{
//create a blank bitmap the same size as original
Bitmap newBitmap = new Bitmap(source.Width, source.Height);
//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);
// create the negative color matrix
ColorMatrix colorMatrix = new ColorMatrix(new float[][]
{
new float[] {-1, 0, 0, 0, 0},
new float[] {0, -1, 0, 0, 0},
new float[] {0, 0, -1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {1, 1, 1, 0, 1}
});
// create some image attributes
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
//dispose the Graphics object
g.Dispose();
return newBitmap;
}
Fast alternative to using a ColorMatrix for pixel manipulation:
public static void BitmapInvertColors(Bitmap bitmapImage)
{
var bitmapRead = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
var bitmapLength = bitmapRead.Stride * bitmapRead.Height;
var bitmapBGRA = new byte[bitmapLength];
Marshal.Copy(bitmapRead.Scan0, bitmapBGRA, 0, bitmapLength);
bitmapImage.UnlockBits(bitmapRead);
for (int i = 0; i < bitmapLength; i += 4)
{
bitmapBGRA[i] = (byte)(255 - bitmapBGRA[i]);
bitmapBGRA[i + 1] = (byte)(255 - bitmapBGRA[i + 1]);
bitmapBGRA[i + 2] = (byte)(255 - bitmapBGRA[i + 2]);
// [i + 3] = ALPHA.
}
var bitmapWrite = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
Marshal.Copy(bitmapBGRA, 0, bitmapWrite.Scan0, bitmapLength);
bitmapImage.UnlockBits(bitmapWrite);
}
VB version of Dan's Answer. It works like a charm !!
Public Function Transform(source As Bitmap) As Bitmap
'create a blank bitmap the same size as original
Dim newBitmap As New Bitmap(source.Width, source.Height)
'get a graphics object from the new image
Dim g As Graphics = Graphics.FromImage(newBitmap)
' create the negative color matrix
Dim colorMatrix As New ColorMatrix(New Single()() {New Single() {-1, 0, 0, 0, 0}, New Single() {0, -1, 0, 0, 0}, New Single() {0, 0, -1, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {1, 1, 1, 0, 1}})
' create some image attributes
Dim attributes As New ImageAttributes()
attributes.SetColorMatrix(colorMatrix)
g.DrawImage(source, New Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, _
GraphicsUnit.Pixel, attributes)
'dispose the Graphics object
g.Dispose()
Return newBitmap
End Function
You aren't setting Matrix33 or Matrix44. My understanding is that Matrix33 would be the alpha component, so I suspect you're making your entire image transparent.
Try setting Matrix33 = 1.
I used "SIMD Supported Vectors" to make a code faster then pointers.Its under System.Numerics namespace.But before using these classes you need to get the update for System.Numerics from NuGet.Just search for System.Numerics.Anyways thats my class to invert the image
public class VBitmap : IDisposable
{
public short Width { get; private set; }
public short Height { get; private set; }
public int Stride { get; private set; }
public int PixelLenght { get; private set; }
public byte BytesperPixel { get; private set; }
public PixelFormat PixelFormat { get; private set; }
public byte[] Pixels { get; private set; }
public VBitmap(string path)
{
using (Bitmap bmp = new Bitmap(path))
{
BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
Width = checked((short)bmp.Width);
Height = checked((short)bmp.Height);
Stride = bmpdata.Stride;
PixelLenght = Stride * Height;
BytesperPixel = checked((byte)(Stride / Width));
PixelLenght = (PixelLenght % 16) != 0 ? PixelLenght + (PixelLenght % 16) : PixelLenght;
PixelFormat = bmp.PixelFormat;
Pixels = new byte[PixelLenght];
Marshal.Copy(bmpdata.Scan0, Pixels, 0, PixelLenght);
bmp.UnlockBits(bmpdata);
}
}
~VBitmap()
{
Dispose();
}
public void InvertPixels()
{
byte[] resultarray = Pixels;
unsafe
{
fixed (byte* result_ptr = resultarray)
{
for (int i = 0; i < PixelLenght; i += 16)
(~new Vector<byte>(Pixels, i)).CopyTo(resultarray, i);
}
}
}
public void InvertPixels(string name)
{
byte[] resultarray = Pixels;
unsafe
{
fixed (byte* result_ptr = resultarray)
{
for (int i = 0; i < PixelLenght; i += 16)
(~new Vector<byte>(Pixels, i)).CopyTo(resultarray, i);
SaveImage(name);
}
}
}
public unsafe void SaveImage(string name)
{
fixed (byte* p_ptr = Pixels)
{
using (Bitmap resultbmp = new Bitmap(Width, Height, Stride, PixelFormat, (IntPtr)p_ptr))
{
resultbmp.Save(name, ImageFormat.Jpeg);
}
}
}
public void Dispose()
{
Width = 0;
Height = 0;
Stride = 0;
PixelLenght = 0;
BytesperPixel = 0;
Pixels = null;
GC.Collect();
}
}
Usage.Note:To get best performance from vectors you need to run your code on Release Mode:
static void Main(string[] args)
{
new VBitmap("testp.png").InvertPixels("qq.jpg");//Inverts the given bitmap and saves it.
}
By inverting, do you mean creating a negative? If yes here is a snippet:
public void ApplyInvert()
{
byte A, R, G, B;
Color pixelColor;
for (int y = 0; y < bitmapImage.Height; y++)
{
for (int x = 0; x < bitmapImage.Width; x++)
{
pixelColor = bitmapImage.GetPixel(x, y);
A = pixelColor.A;
R = (byte)(255 - pixelColor.R);
G = (byte)(255 - pixelColor.G);
B = (byte)(255 - pixelColor.B);
bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
}
}
}
from: http://www.smokycogs.com/blog/image-processing-in-c-sharp-inverting-an-image/
If you want read more about your problem and color matrix, please proceed with the following link: https://web.archive.org/web/20141230042200/http://bobpowell.net/negativeimage.aspx
var gfxPicture = Graphics.FromImage(img);
==>
var gfxPicture = Graphics.FromImage(bmpPicture);
DrawImage could distort image, GetPixel is slow, Try WPF imaging API

Nvidia 3d Video using DirectX11 and SlimDX in C#

Good day,
I am trying to display a real-time stereo video using nvidia 3DVision and two IP cameras. I am totally new to DirectX, but have tried to work through some tutorials and other questions on this and other sites. For now, I am displaying two static bitmaps for left and right eyes. These will be replaced by bitmaps from my cameras once I have got this part of my program working.
This question NV_STEREO_IMAGE_SIGNATURE and DirectX 10/11 (nVidia 3D Vision) has helped me quite a bit, but I am still struggling to get my program working as it should. What I am finding is that my shutter glasses start working as they should, but only the image for the right eye gets displayed, while the left eye remains blank (except for the mouse cursor).
Here is my code for generating the stereo images:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.Windows;
using SlimDX.DXGI;
using Device = SlimDX.Direct3D11.Device; // Make sure we use DX11
using Resource = SlimDX.Direct3D11.Resource;
namespace SlimDxTest2
{
static class Program
{
private static Device device; // DirectX11 Device
private static int Count; // Just to make sure things are being updated
// The NVSTEREO header.
static byte[] stereo_data = new byte[] {0x4e, 0x56, 0x33, 0x44, //NVSTEREO_IMAGE_SIGNATURE = 0x4433564e;
0x00, 0x0F, 0x00, 0x00, //Screen width * 2 = 1920*2 = 3840 = 0x00000F00;
0x38, 0x04, 0x00, 0x00, //Screen height = 1080 = 0x00000438;
0x20, 0x00, 0x00, 0x00, //dwBPP = 32 = 0x00000020;
0x02, 0x00, 0x00, 0x00}; //dwFlags = SIH_SCALE_TO_FIT = 0x00000002
[STAThread]
static void Main()
{
Bitmap left_im = new Bitmap("Blue.png"); // Read in Bitmaps
Bitmap right_im = new Bitmap("Red.png");
// Device creation
var form = new RenderForm("Stereo test") { ClientSize = new Size(1920, 1080) };
var desc = new SwapChainDescription()
{
BufferCount = 1,
ModeDescription = new ModeDescription(1920, 1080, new Rational(120, 1), Format.R8G8B8A8_UNorm),
IsWindowed = false, //true,
OutputHandle = form.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
SwapChain swapChain;
Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
RenderTargetView renderTarget; // create a view of our render target, which is the backbuffer of the swap chain we just created
using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
renderTarget = new RenderTargetView(device, resource);
var context = device.ImmediateContext; // set up a viewport
var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
context.OutputMerger.SetTargets(renderTarget);
context.Rasterizer.SetViewports(viewport);
// prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
using (var factory = swapChain.GetParent<Factory>())
factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);
form.KeyDown += (o, e) => // handle alt+enter ourselves
{
if (e.Alt && e.KeyCode == Keys.Enter)
swapChain.IsFullScreen = !swapChain.IsFullScreen;
};
form.KeyDown += (o, e) => // Alt + X -> Exit Program
{
if (e.Alt && e.KeyCode == Keys.X)
{
form.Close();
}
};
context.ClearRenderTargetView(renderTarget, Color.Green); // Fill Screen with specified colour
Texture2DDescription stereoDesc = new Texture2DDescription()
{
ArraySize = 1,
Width = 3840,
Height = 1081,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Staging,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
// Main Loop
MessagePump.Run(form, () =>
{
Texture2D texture_stereo = Make3D(left_im, right_im); // Create Texture from two bitmaps in memory
ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = 1080, Left = 0, Right = 1920 };
context.CopySubresourceRegion(texture_stereo, 0, stereoSrcBox, renderTarget.Resource, 0, 0, 0, 0);
texture_stereo.Dispose();
swapChain.Present(0, PresentFlags.None);
});
// Dispose resources
swapChain.IsFullScreen = false; // Required before swapchain dispose
device.Dispose();
swapChain.Dispose();
renderTarget.Dispose();
}
static Texture2D Make3D(Bitmap leftBmp, Bitmap rightBmp)
{
var context = device.ImmediateContext;
Bitmap left2 = leftBmp.Clone(new RectangleF(0, 0, leftBmp.Width, leftBmp.Height), PixelFormat.Format32bppArgb); // Change bmp to 32bit ARGB
Bitmap right2 = rightBmp.Clone(new RectangleF(0, 0, rightBmp.Width, rightBmp.Height), PixelFormat.Format32bppArgb);
// Show FrameCount on screen: (To test)
Graphics left_graph = Graphics.FromImage(left2);
left_graph.DrawString("Frame: " + Count.ToString(), new System.Drawing.Font("Arial", 16), Brushes.Black, new PointF(100, 100));
left_graph.Dispose();
Graphics right_graph = Graphics.FromImage(right2);
right_graph.DrawString("Frame: " + Count.ToString(), new System.Drawing.Font("Arial", 16), Brushes.Black, new PointF(200, 200));
right_graph.Dispose();
Count++;
Texture2DDescription desc2d = new Texture2DDescription()
{
ArraySize = 1,
Width = 1920,
Height = 1080,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Staging,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
Texture2D leftText2 = new Texture2D(device, desc2d); // Texture2D for each bmp
Texture2D rightText2 = new Texture2D(device, desc2d);
Rectangle rect = new Rectangle(0, 0, left2.Width, left2.Height);
BitmapData leftData = left2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
IntPtr left_ptr = leftData.Scan0;
int left_num_bytes = Math.Abs(leftData.Stride) * leftData.Height;
byte[] left_bytes = new byte[left_num_bytes];
byte[] left_bytes2 = new byte[left_num_bytes];
System.Runtime.InteropServices.Marshal.Copy(left_ptr, left_bytes, 0, left_num_bytes); // Get Byte array from bitmap
left2.UnlockBits(leftData);
DataBox box1 = context.MapSubresource(leftText2, 0, MapMode.Write, SlimDX.Direct3D11.MapFlags.None);
box1.Data.Write(left_bytes, 0, left_bytes.Length);
context.UnmapSubresource(leftText2, 0);
BitmapData rightData = right2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
IntPtr right_ptr = rightData.Scan0;
int right_num_bytes = Math.Abs(rightData.Stride) * rightData.Height;
byte[] right_bytes = new byte[right_num_bytes];
System.Runtime.InteropServices.Marshal.Copy(right_ptr, right_bytes, 0, right_num_bytes); // Get Byte array from bitmap
right2.UnlockBits(rightData);
DataBox box2 = context.MapSubresource(rightText2, 0, MapMode.Write, SlimDX.Direct3D11.MapFlags.None);
box2.Data.Write(right_bytes, 0, right_bytes.Length);
context.UnmapSubresource(rightText2, 0);
Texture2DDescription stereoDesc = new Texture2DDescription()
{
ArraySize = 1,
Width = 3840,
Height = 1081,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Staging,
MipLevels = 1,
SampleDescription = new SampleDescription(1, 0)
};
Texture2D stereoTexture = new Texture2D(device, stereoDesc); // Texture2D to contain stereo images and Nvidia 3DVision Signature
// Identify the source texture region to copy (all of it)
ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = 1080, Left = 0, Right = 1920 };
// Copy it to the stereo texture
context.CopySubresourceRegion(leftText2, 0, stereoSrcBox, stereoTexture, 0, 0, 0, 0);
context.CopySubresourceRegion(rightText2, 0, stereoSrcBox, stereoTexture, 0, 1920, 0, 0); // Offset by 1920 pixels
// Open the staging texture for reading and go to last row
DataBox box = context.MapSubresource(stereoTexture, 0, MapMode.Write, SlimDX.Direct3D11.MapFlags.None);
box.Data.Seek(stereoTexture.Description.Width * (stereoTexture.Description.Height - 1) * 4, System.IO.SeekOrigin.Begin);
box.Data.Write(stereo_data, 0, stereo_data.Length); // Write the NVSTEREO header
context.UnmapSubresource(stereoTexture, 0);
left2.Dispose();
leftText2.Dispose();
right2.Dispose();
rightText2.Dispose();
return stereoTexture;
}
}
}
I have tried various methods of copying the Texture2D of the stereo image including signature (3840x1081) to the backbuffer, but none of the methods I have tried display both images...
Any help or comments will be much appreciated,
Ryan
If using DirectX11.1 is an option, there is a much easier way to enable stereoscopic features, without having to rely on nVidia's byte wizardry. Basically, you create a SwapChan1 instead of a regular SwapChain, then it is as simple as setting Stereo to True.
Have a look at this post I made, it shows you how to create a Stereo swapChain. The code is a porting to C# of MS's own stereo sample. Then you'll have two render targets and it is much more simple. Before rendering you have to:
void RenderEye(bool rightEye, ITarget target)
{
RenderTargetView currentTarget = rightEye ? target.RenderTargetViewRight : target.RenderTargetView;
context.OutputMerger.SetTargets(target.DepthStencilView, currentTarget);
[clean color/depth]
[render scene]
[repeat for each eye]
}
where ITarget is an interface for a class providing access to the backbuffer, rendertargets, etc.
That's it, DirectX will take care of everything. Hope this helps.
Try creating the backbufer with width = 1920 and not 3840.
stretch each image to half the size in width and put them side by side.
I remember seeing this exact same question while searching a couple of days ago on the Nvidia Developer forums. Unfortunately the forums are down due to a recent hacker attack. I remember that the OP on that thread was able to get it working with DX11 and Slimdx using the signature hack. You do not use the stretchRectangle method its was something like createResuroseRegion() or but not that exactly I can't remember. It might be these methods CopyResource() or CopySubresourceRegion() found in this similar thread on stack over flow.
Copy Texture to Texture
Also are you rendering the image continuously or at least a few times? I was doing the same thing in DX9 and had to tell DX to render 3 frames before the driver recognized it as 3D vision. Did your glasses kick on? Is your backbuffer = (width*2), (Height+1) and are you writing the backbuffer like so:
_________________________
| | |
| img1 | img2 |
| | |
--------------------------
|_______signature________| where this last row = 1 pix tall

Create image thumbnail with rounded corners

I need to create a thumbnail image with transparent rounded corners. Before this requirement I used the simple:
using (var b = new Bitmap(dataSize.Width, dataSize.Height, PixelFormat.Format32bppArgb))
using (var g = Graphics.FromImage(b))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
g.DrawImage(original, 0, 0, b.Width, b.Height);
}
which produced great results (for reductions to approx 50x50px) even without any interpolation. Now with the rounded corners I used the following algorithm (the 4 'if's are there so I can have variable roundness on each of the 4 corners):
using (var b = new Bitmap(dataSize.Width, dataSize.Height, PixelFormat.Format32bppArgb))
using (var g = Graphics.FromImage(b))
{
// set interpolation
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
// transformation to scale and shift the brush
var transform = new Matrix();
transform.Scale(ratio, ratio);
transform.Translate(start.X / ratio, start.Y / ratio);
var brush = new TextureBrush(original) { Transform = transform };
// create path for stamping the iamge
var gp = new GraphicsPath(FillMode.Winding);
if (descriptor.CornerRadiusLeftTop > 0)
gp.AddArc(descriptor.GetLeftTopCorner(b.Size), 180, 90);
else
gp.AddLine(-1, -1, -1, -1);
if (descriptor.CornerRadiusRightTop > 0)
gp.AddArc(descriptor.GetRightTopCorner(b.Size), 270, 90);
else
gp.AddLine(b.Width + 1, -1, b.Width + 1, -1);
if (descriptor.CornerRadiusRightBottom > 0)
gp.AddArc(descriptor.GetRightBottomCorner(b.Size), 0, 90);
else
gp.AddLine(b.Width + 1, b.Height + 1, b.Width + 1, b.Height + 1);
if (descriptor.CornerRadiusLeftBottom > 0)
gp.AddArc(descriptor.GetLeftBottomCorner(b.Size), 90, 90);
else
gp.AddLine(-1, b.Height + 1, -1, b.Height + 1);
// stamp the image with original
g.FillPath(brush, gp);
}
but this approach produced ugly un-interpolated imaged with really jagged gradients. Is there a better approach to create transparent thumbnails or are there some settings I could use to improve the output?
I've written a blog post which explains exactly how to do this.
http://danbystrom.se/2008/08/24/soft-edged-images-in-gdi/
If you look at the first sample images, you're seeing 5) and I show how to arrive at 6). Good luck.
I would first copy the image to second one with rounded corners, then use GetThumbnailImage to scale it down.
I've used a modified TransferChannel method to add mask, which is not unsafe as in blog post by danbystrom.
public static void TransferChannel(Bitmap src, Bitmap dst, ChannelARGB sourceChannel, ChannelARGB destChannel)
{
if (src.Size != dst.Size)
throw new ArgumentException();
var r = new Rectangle(Point.Empty, src.Size);
var bdSrc = src.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
var bdDst = dst.LockBits(r, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
var s = bdSrc.Stride * src.Height;
var baSrc = new byte[s];
var baDst = new byte[s];
Marshal.Copy(bdSrc.Scan0, baSrc, 0, s);
Marshal.Copy(bdDst.Scan0, baDst, 0, s);
for (var counter = 0; counter < baSrc.Length; counter += 4)
baDst[counter + (int)destChannel] = baSrc[counter + (int)sourceChannel];
Marshal.Copy(baDst, 0, bdDst.Scan0, s);
src.UnlockBits(bdSrc);
dst.UnlockBits(bdDst);
}
And my method to resize and make rounded corners is:
var b = new Bitmap(dataSize.Width, dataSize.Height, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(b))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(original, start.X, start.Y, original.Width * ratio, original.Height * ratio);
if (hasRoundedCorners)
using (var mask = CreateMask(dataSize, radius))
TransferChannel(mask, b, ChannelARGB.Blue, ChannelARGB.Alpha);
}
return b;

Categories