null values on integers and strings but they are already assigned - c#

i am having a little problem, VS gives me 2 warnings about two values (int[] and string[]) that are null because they are never assigned, but im sure i assigned them, this is the part of the code that is relevant to my problem:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.IO;
namespace DA_Story_Editor
{
public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm
{
public Form1()
{
InitializeComponent();
}
int[] pntrs;
string[] Strs;
private void ReadFile(string path1)
{
FileStream stream = new FileStream(path1, FileMode.Open, FileAccess.Read);
for (int i = 0; i < Pntrnum; i++)
{
stream.Position = Pntrstrt;
stream.Read(data, 0, data.Length);
pntrs[i] = BitConverter.ToInt32(data, 0);
}
for (int i = 0; i < Pntrnum; i++)
{
byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]];
stream.Position = pntrs[i];
stream.Read(sttrings, 0, sttrings.Length);
Strs[i] = Encoding.GetEncoding("SHIFT-JIS").GetString(sttrings);
ListViewItem item = new ListViewItem(new string[]
{
pntrs[i].ToString("X"),
Strs[i],
Strs[i],
});
listView1.Items.AddRange(new ListViewItem[] {item});
}
}
}
}
im not sure why it does give me those warnings, and btw it also gives me a "NullReferenceException" on the line: pntrs[i] = BitConverter.ToInt32(data, 0);

You're never constructing and assigning the variable itself - but you try to use the array:
// Need to add:
pntrs = new int[Pntrnum];
for (int i = 0; i < Pntrnum; i++)
{
stream.Position = Pntrstrt;
stream.Read(data, 0, data.Length);
pntrs[i] = BitConverter.ToInt32(data, 0);
}
// Need to add:
Strs = new string[Pntrnum];
for (int i = 0; i < Pntrnum; i++)
{
byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]];
stream.Position = pntrs[i];
stream.Read(sttrings, 0, sttrings.Length);
Strs[i] = Encoding.GetEncoding("SHIFT-JIS").GetString(sttrings);

Related

How to convert OpenCV 2.4 source to 3.0 In c#

Difficulty in source conversion
I have looked up the internal functions and related documentation supported by the DLL, but I have difficulty finding matching functions or data types.
[Calibration Find value]
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using OpenCvSharp;`
namespace Project_NFT
{
class CalibrateCamera
{
public const string ImageCalibration = "C:\\Users\\JL\\Documents\\Visual Studio 2008\\Projects\\Project NET\\Project NFT\\Image/{0:D2}.jpg";
public CalibrateCamera()
{
const int IMAGE_NUM = 3;
const int PAT_ROW = 7;
const int PAT_COL = 10;
const int PAT_SIZE = PAT_ROW * PAT_COL;
const int ALL_POINTS = IMAGE_NUM * PAT_SIZE;
const float CHESS_SIZE = 24.0f;
CvSize patternSize = new CvSize(PAT_COL, PAT_ROW);
IplImage[] srcImg = new IplImage[IMAGE_NUM];
for (int i = 0; i < IMAGE_NUM; i++)
{
string path = string.Format(ImageCalibration, i);
srcImg[i] = new IplImage(path, LoadMode.Color);
}
CvPoint3D32f[] objects = new CvPoint3D32f[ALL_POINTS];
for (int i = 0; i < IMAGE_NUM; i++)
{
for (int j = 0; j < PAT_ROW; j++)
{
for (int k = 0; k < PAT_COL; k++)
{
objects[(i * PAT_SIZE) + (j * PAT_COL) + k] = new CvPoint3D32f
{
X = j * CHESS_SIZE,
Y = k * CHESS_SIZE,
Z = 0.0f
};
}
}
}
CvMat objectPoints = new CvMat(ALL_POINTS, 3, MatrixType.F32C1, objects);
int foundNum = 0;
List<CvPoint2D32f> allCorners = new List<CvPoint2D32f>(ALL_POINTS);
int[] pCount = new int[IMAGE_NUM];
using (CvWindow window = new CvWindow("Calibration", WindowMode.AutoSize))
{
for (int i = 0; i < IMAGE_NUM; i++)
{
CvPoint2D32f[] corners;
bool found = Cv.FindChessboardCorners(srcImg[i], patternSize, out corners);
Debug.Print("{0:D2}...", i);
if (found)
{
Debug.Print("ok");
foundNum++;
}
else
{
Debug.Print("fail");
}
using (IplImage srcGray = new IplImage(srcImg[i].Size, BitDepth.U8, 1))
{
Cv.CvtColor(srcImg[i], srcGray, ColorConversion.BgrToGray);
Cv.FindCornerSubPix(srcGray, corners, corners.Length, new CvSize(3, 3), new CvSize(-1, -1), new CvTermCriteria(20, 0.03));
Cv.DrawChessboardCorners(srcImg[i], patternSize, corners, found);
pCount[i] = corners.Length;
window.ShowImage(srcImg[i]);
Cv.WaitKey(0);
}
allCorners.AddRange(corners);
}
if (foundNum != IMAGE_NUM)
{
Debug.Assert(false);
}
}
CvMat imagePoints = new CvMat(ALL_POINTS, 1, MatrixType.F32C2, allCorners.ToArray());
CvMat pointCounts = new CvMat(IMAGE_NUM, 1, MatrixType.S32C1, pCount);
CvMat intrinsic, distortion, rotation, translation;
Cv.CalibrateCamera2(objectPoints, imagePoints, pointCounts, new CvSize(640, 480), out intrinsic, out distortion, out rotation, out translation, CalibrationFlag.Default);
CvMat subImagePoints, subObjectPoints;
Cv.GetRows(imagePoints, out subImagePoints, 0, PAT_SIZE);
Cv.GetRows(objectPoints, out subObjectPoints, 0, PAT_SIZE);
Cv.FindExtrinsicCameraParams2(subObjectPoints, subImagePoints, intrinsic, distortion, out rotation, out translation);
using (CvFileStorage fs = new CvFileStorage("camera.xml", null, FileStorageMode.Write))
{
fs.Write("intrinsic", intrinsic);
fs.Write("rotation", rotation);
fs.Write("translation", translation);
fs.Write("distortion", distortion);
}
foreach (IplImage img in srcImg)
{
img.Dispose();
}
Console.WriteLine(File.ReadAllText("camera.xml"));
Console.Read();
}
}
}
[Calibration Apply Value]
CvMat intrinsic, distortion, extrinsic;
CvFileNode param;
using (CvFileStorage fs = new CvFileStorage("camera.xml", null, FileStorageMode.Read))
{
param = Cv.GetFileNodeByName (fs, null, "intrinsic");
intrinsic = fs.Read<CvMat>(param);
param = Cv.GetFileNodeByName (fs, null, "distortion");
distortion = fs.Read<CvMat>(param);
}
Cv.FindExtrinsicCameraParams2(object_points, image_points,intrinsic, distortion,
out rotation_vector, out translation_vector);
The source is the Camera Calibration reference, which is difficult to convert

C# Bitmap: System.ArgumentException "Invalid parameter."

Faced such a problem "System.ArgumentException", while writing an envelope from an image (.jpg) in a text file with a picture (ASCII). Did according to the instructions (https://www.bilibili.com/video/av5862027/)
For the second or third day I try to solve this problem.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
namespace ayy
{
class Program
{
static void Main(string[] args)
{
FileStream stream = new FileStream(#"meme.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);
for (int imageNumber = 0; imageNumber <= 7600; imageNumber++)
{
string url = #"C:\Users\Admin\source\repos\badapple\ayy\ba\ba";
if (imageNumber < 10)
{
url += "00000";
}
else if (imageNumber < 100)
{
url += "0000";
}
else if (imageNumber < 1000)
{
url += "000";
}
else
{
url += "00";
}
url += imageNumber.ToString() + ".jpg";
Bitmap image = new Bitmap(url, true);
for (int y = 0; y < image.Height; y++)
{
string str = "";
for (int x = 0; x < image.Width; x++)
{
Color pixel = image.GetPixel(x, y);
if (pixel.R > 200)
{
str += "#";
}
else
{
str += " ";
}
writer.WriteLine(str);
}
Console.WriteLine(url);
}
writer.Close();
}
}
}
}
using, using, using
Every time you go to play with something (or create an object) check if you can use a using statement
If you expect a file to be there, do some due diligence and check if it exists
If you want to join paths and file names, use Path.Combine()
GetPixel is extremely slow, so probably better to use LockBits
Why use lots of ifs to add 0's when you can use a format specifier $"{imageNumber:D5}.jpg"
Truthfully, i am not sure if this will fix your problem, but you are much better place regardless
using (var stream = new FileStream(#"meme.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (var writer = new StreamWriter(stream))
{
for (var imageNumber = 0; imageNumber <= 7600; imageNumber++)
{
var dir = #"C:\Users\Admin\source\repos\badapple\ayy\ba\ba";
var fileName = Path.Combine(dir, $"{imageNumber:D5}.jpg");
if (File.Exists(fileName))
{
throw new FileNotFoundException($"Woah, what now : {fileName}");
}
using (var image = new Bitmap(fileName, true))
{
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var pixel = image.GetPixel(x, y);
writer.Write(pixel.R > 200 ? "#" : " ");
}
writer.WriteLine();
}
}
}
}
}
If you are still having problems, work out what file is causing the problem, check to see if it is actually an image and loads. My spidey senses tells me its not

System.Drawing Error : Parameter is not valid

I've encountered a problem during processing an image using c# , when I try to save my Image. the error is coming from system.drawing , which says parameter is invalid,here is my complete code , any ideas?!
thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Collections;
namespace ipp
{
class Program
{
public static byte[] ImageToArray(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
}
public static Image ArrayToImage(byte[] imageBytes)
{
using (var ms = new MemoryStream(imageBytes))
{
return Image.FromStream(ms);
}
}
static void Main(string[] args)
{
Console.WriteLine("Welcome, The Operation Has Begun.");
var img = new System.Drawing.Bitmap(#"E:\gray.bmp");
byte[] image1 = ImageToArray(img, System.Drawing.Imaging.ImageFormat.Bmp);
BitArray bits = new BitArray(image1);
byte[] subar0 = new byte[image1.Length];
byte[] subar1 = new byte[image1.Length];
byte[] subar2 = new byte[image1.Length];
byte[] subar3 = new byte[image1.Length];
byte[] subar4 = new byte[image1.Length];
byte[] subar5 = new byte[image1.Length];
byte[] subar6 = new byte[image1.Length];
byte[] subar7 = new byte[image1.Length];
byte[] subarf = new byte[image1.Length];
for (int i = 0; i < bits.Length; i += 8)
{
subar0[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 1; i < bits.Length; i += 8)
{
subar1[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 2; i < bits.Length; i += 8)
{
subar2[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 3; i < bits.Length; i += 8)
{
subar3[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 4; i <= bits.Length; i += 8)
{
subar4[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 5; i < bits.Length; i += 8)
{
subar5[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 6; i < bits.Length; i += 8)
{
subar6[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 7; i < bits.Length; i += 8)
{
subar7[i / 8] = Convert.ToByte(bits[i]);
}
for (int i = 0; i < image1.Length; i++)
{
subarf[i] = Convert.ToByte(128 * subar0[i] + 64 * subar1[i]);
}
Image fout = ArrayToImage(subarf);
fout.Save("E:\\merge.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
}
}

NPOI AutoSizeColumn not resizing correctly

I've put the .AutoSizeColumn right before the write Method
int numberOfColumns = sheet.GetRow(rowcount - 1).PhysicalNumberOfCells;
for (int i = 0; i <= numberOfColumns; i++)
{
sheet.AutoSizeColumn(i);
GC.Collect();
}
using (var fileData = new FileStream(#"C:\Temp\Contatti.xlsx", FileMode.Create))
{
wb.Write(fileData);
}
this is an example of the result
The problem also migh be, that PhysicalNumberOfCells can return 1, even if you have a cell lets say in 'Z' column. There is LastCellNum property,you i instead of PhysicalNumberOfCells:
int lastColumNum = sheet.GetRow(0).LastCellNum;
for (int i = 0; i <= lastColumNum; i++)
{
sheet.AutoSizeColumn(i);
GC.Collect();
}
using (var fileData = new FileStream(#"D:\Contatti.xlsx", FileMode.Create))
{
wb.Write(fileData);
}

Combining arrays created via multiple threads

I have been trying to create couple of 2-D arrays via multi-threading. Each threading will generate a small 2-D array. All of the 2-D will be consolidated and that is where I am having issue. I commented "//!this is causing error" towards the bottom of SimulatingMethod method. Please share your insight. Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample
{
class Program
{
static void Main(string[] args)
{
double[,] randSims;
randSims = SimulatingClass.SimulatingMethod();
}
}
class SimulatingClass
{
public static double[,] SimulatingMethod()
{
int rowCount = 9;
int columnCount = 1;
int NumberOfCores = System.Environment.ProcessorCount;
int RowsForEachThread = rowCount / NumberOfCores;
Thread[] arrayOfThread = new Thread[NumberOfCores];
DataStuff[] dataStuff= new DataStuff[NumberOfCores];
for (int i = 0; i < NumberOfCores; i++)
{
dataStuff[i] = new DataStuff(RowsForEachThread, columnCount);
arrayOfThread[i] = new Thread(new ThreadStart(dataStuff[i].UpdateMatrixData));
arrayOfThread[i].Name = "Thread" + i;
arrayOfThread[i].Start();
}
for (int i = 0; i < NumberOfCores; i++)
{
arrayOfThread[i].Join();
}
//start combining arrays from different threads
var list = new List<double[,]>();
for (int m = 0; m < NumberOfCores; m++)
{
list.AddRange(dataStuff[m]); //!this is causing error
}
//trying to convert list back to array
double[,] array3 = list.ToArray(); //!this is causing error
return array3;
}
}
class DataStuff
{
public double G;
public double[,] M;
public long steps, trials;
public DataStuff(long _steps, long _trials)
{
M = new Double[_steps, _trials]; // <- M is created in the constructor
G = 60;
steps = _steps;
trials = _trials;
}
public void UpdateMatrixData()
{
for (int i = 0; i < steps; i++)
{
for (int j = 0; j < trials; j++)
{
M[i, j] = i + j;
}
}
}
}
}
You should specify the property as follows:
list.Add(dataStuff[m].M);
It's because the dataStuff[m] is of type DataStuff, but the type double[,] expected as the list item.
If I understood you correctly, you need a consolidated 2D array. Try to declare it initially with desired dimensions:
double[,] array3 = new double[rowCount, columnCount];
And copy data from dataStuff array to it after processing:
for (int m = 0; m < NumberOfCores; m++)
{
Array.Copy(dataStuff[m].M, 0, array3, m * columnCount * RowsForEachThread, dataStuff[m].M.Length);
}
return array3;
And you don't need list at all.
Please note, that you have possible problems related to the rounding:
int RowsForEachThread = rowCount / NumberOfCores;
You should handle the situation when the rowCount is not divisible by the NumberOfCores.

Categories

Resources