Processing image stops mid-loop for no reason c# - c#

I have an image, and I want to take each square of 256X256 pixels, find the mean color, and draw that square with said color.
Problem: it seems that after the first square the processing suddenly stops, but after following the program I can see the indexes are just fine. I have no idea if the problem lies with file writing in my computer system, or a wrong use of the "Bitmap" class functions.
original:
result:
code:
public const int big =256;
public const int small = 16;
static void Main(string[] args)
{
Bitmap bt = new Bitmap(#"C:\Users\mishe\Desktop\00_sorted images - training\general shores\agulhas_oli_2016146_lrg.jpg");
Bitmap bt2 = bt;
Color MeanColor;
double r = 0;
double g = 0;
double b = 0;
int i = 0;
int j = 0;
//big loop to go over all image
for (i = 0; i < bt.Height-257; i+=256)
{
for (j = 0; j < bt.Width-257; j+=256)
{
/////////////////////////////
//small loop on 1 square to get the mean color of the area
for (int x = i; x < big; x++)
{
for (int y = j; y < big; y++)
{
r += bt.GetPixel(x, y).R;
g += bt.GetPixel(x, y).G;
b += bt.GetPixel(x, y).B;
}
}
/////////////////////////////
r = r / Math.Pow(big, 2);
g = g / Math.Pow(big, 2);
b = b / Math.Pow(big, 2);
MeanColor = Color.FromArgb((int)r, (int)g, (int)b);
/////////////////////////////
//small loop on the same square to set the color
for (int x = i; x < big; x++)
{
for (int y = j; y < big; y++)
{
bt2.SetPixel(x, y, MeanColor);
}
}
/////////////////////////////
}
}
bt2.Save(#"C:\Users\mishe\Desktop\compressed image.jpg", ImageFormat.Jpeg);
}

This line:
//small loop on 1 square to get the mean color of the area
for (int x = i; x < big; x++)
After the first square, x will be 256, so it won't do the small loop.
I think you want:
for (int x = i; x < i + big; x++)
Or your small loop could be:
for (int x = 1; x < big; x++)
and then add the large and small values inside the loop:
r += bt.GetPixel(i + x, j + y).R;

Related

Parallize elementwise matrix (2dArray) calculations

This is my first question and I'm relatively new to C#. (Excuse my bad English)
I'm writing a template matching algorithm in C# using the .NET Framework with a WindowsForms Application in Visual Studio. Sadly the new indices and ranges functions from C#8.0, especially the range operator (..), didn't get implemented in the .NET Framework. I know there is a workaround for this as you can see in this thread but it is not supported by Microsoft. So I'm searching for another way to parallelize my elementwise 2dArray (matrix) calculations to make my program faster.
In my program, I'm calculating the differential square (ds) of an area (with the size of my template) inside a 2dArray (my image) and a 2dArray (my template). These values a written to a new 2dAary (DS) which holds all differential squares in the corresponding positions to the image. I can search the indices of DS where the differential square is minimal which is equal to the matching position (highest correspondence between template and image) of the template inside the image.
In python the calculation of DS is very quick using the index range operator (:) and will look like this:
H,W = I.shape # read out Height H & Width W from Image I
h,w = T.shape # read out Height h & Width w from Template T
for i in range(H-h+1):
for j in range(W-w+1):
DS[i,j] = np.sum((I[i:i+h,j:j+w] - T)**2)
But in C# I have to make the calculation of DS elementwise therefore it looks like this and takes for ever:
int Tw = template.Width;
int Th = template.Height;
int Iw = image.Width;
int Ih = image.Height;
int d = 0;
int[,] ds = new int[Tw, Th];
int[,] DS = new int[Iw - Tw + 1, Ih - Th + 1];
for (int y = 0; y < Ih - Th + 1; y++)
{
for (int x = 0; x < Iw - Tw + 1; x++)
{
for (int yT = 0; yT < Th; yT++)
{
for (int xT = 0; xT < Tw; xT++)
{
d = I[x + xT, y + yT] - T[xT, yT];
ds[xt, yt] = d * d;
}
}
int sum = ds.Cast<int>().Sum();
DS[x, y] = sum;
}
}
I know that I could use threads but that would be a little complex for me.
Or maybe I could use CUDA with my Nvidia GPU to speed things up a little.
But I am asking you and myself is there another way to parallelize (optimize) my elementwise 2dArray calculations?
I look forward to any help.
Many thanks in advance!!!
EDIT:
Here I have a working example of my code for a .NET Framework Console App. As you can see I make a lot of elementwise 2d and 3d Array calculations which I would like to process in parallel (or perform them faster in any other way):
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TemplateMatcher_Console
{
class Program
{
public static int[,,] bitmapToMatrix(Bitmap bmp)
{
int[,,] I = new int[bmp.Width, bmp.Height, 3];
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Color pix = bmp.GetPixel(x, y);
I[x, y, 0] = Convert.ToInt32(pix.R);
I[x, y, 1] = Convert.ToInt32(pix.G);
I[x, y, 2] = Convert.ToInt32(pix.B);
}
}
return I;
}
public static int[] indexOfMiniumValue(int[,] matrix)
{
int value = 0;
int minValue = 999999999;
int minFirstIndex = 0;
int minSecondIndex = 0;
int[] ij = new int[2];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
value = matrix[i, j];
if (value < minValue)
{
minValue = value;
minFirstIndex = i;
minSecondIndex = j;
}
}
}
ij[0] = minFirstIndex;
ij[1] = minSecondIndex;
return ij;
}
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
// Deklaration & Eingabe
Console.WriteLine("Type the filepath for your image and then press Enter");
string im = Console.ReadLine();
Console.WriteLine("\nType the filepath for your template and then press Enter");
string temp = Console.ReadLine();
Bitmap template = new Bitmap(#temp);
Bitmap image = new Bitmap(#im);
int Tw = template.Width;
int Th = template.Height;
int Iw = image.Width;
int Ih = image.Height;
int[,] ds = new int[Tw, Th];
int[,] DS = new int[Iw - Tw + 1, Ih - Th + 1];
int[,,] DS_rgb = new int[Iw - Tw + 1, Ih - Th + 1, 3];
int[] xy = new int[2];
// Verarbeitung
// int[,,] I = Array.ConvertAll(image_I, new Converter<byte, int>(Convert.ToInt32));
int[,,] I = bitmapToMatrix(image);
int[,,] T = bitmapToMatrix(template);
for (int rgb = 0; rgb < 3; rgb++)
{
for (int y = 0; y < Ih - Th + 1; y++)
{
for (int x = 0; x < Iw - Tw + 1; x++)
{
//DS_rgb[x, y, rgb] = (I[x .. x + template.Width, y .. y + template.Height, rgb] - T[0 .. template.Width, 0 .. template.Height, rgb]);
for (int yT = 0; yT < Th; yT++)
{
for (int xT = 0; xT < Tw; xT++)
{
ds[xT, yT] = (I[x + xT, y + yT, rgb] - T[xT, yT, rgb]) * (I[x + xT, y + yT, rgb] - T[xT, yT, rgb]);
}
}
int sum = ds.Cast<int>().Sum();
DS_rgb[x, y, rgb] = sum;
}
}
}
//DS[.., ..] = DS_rgb[.., .., 0] + DS_rgb[.., .., 1] + DS_rgb[.., .., 2];
for (int y = 0; y < Ih - Th + 1; y++)
{
for (int x = 0; x < Iw - Tw + 1; x++)
{
DS[x, y] = DS_rgb[x, y, 0] + DS_rgb[x, y, 1] + DS_rgb[x, y, 2];
}
}
//xy = DS.FindIndex(z => z == Math.Min(DS));
xy = indexOfMiniumValue(DS);
// Ausgabe
// Ausgeben der Matrix DS
/*
Console.WriteLine("\nMatrix with all differtial squares:");
Print2DArray(DS);
*/
Console.WriteLine($"\nPosition of your template in your image (upper left corner): ({xy[0]}, {xy[1]})");
Console.Write("\nPress any key to close the TemplateMatcher console app...");
Console.ReadKey();
}
}
}

Spectral Saliency map from Matlab code to C#.net,

SSM screenshot
Hi, I have implemeted the Spectral Saliency map from Matlab code to C#.net,
But result is some strange.
Result map is not correctly mapped to original image.
What's wrong with me?
Original Matlab code(Octave) is here:
%% Read image from file
inImg = im2double(rgb2gray(imread('1.jpg')));
inImg = imresize(inImg, 64/size(inImg, 2));
%% Spectral Residual
myFFT = fft2(inImg);
myLogAmplitude = log(abs(myFFT));
myPhase = angle(myFFT);
mySpectralResidual = myLogAmplitude - imfilter(myLogAmplitude, fspecial('average', 3), 'replicate');
saliencyMap = abs(ifft2(exp(mySpectralResidual + i*myPhase))).^2;
%% After Effect
saliencyMap = mat2gray(imfilter(saliencyMap, fspecial('gaussian', [10, 10], 2.5)));
imshow(saliencyMap);
My Code is here : C#.net + AForge.net -------------
Windows10, VS2017, AForge & Accord.net
// 이미지 로드
image2 = (Bitmap)pictureBox1.Image;
// 박스 블러
// logAmp smoothing
Accord.Imaging.Filters.FastBoxBlur filtBox1 =
new Accord.Imaging.Filters.FastBoxBlur(3, 3);
// apply the filter
filtBox1.ApplyInPlace(image2);
// 크기줄이기 64x
AForge.Imaging.Filters.ResizeBilinear filtResize =
new AForge.Imaging.Filters.ResizeBilinear(64, 64);
// apply the filter
Bitmap smallImage = filtResize.Apply(image2);
// 2D FFT -------------------------------------------
//cv::merge(planes, 2, complexImg);
AForge.Imaging.ComplexImage complexImage =
AForge.Imaging.ComplexImage.FromBitmap(smallImage);
//double[,] logAmpl = new double[64, 64];
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
//Calculating elementwise complex conjugate of the shifted image 2d vector
complexImage.Data[x, y].Im = 0;
}
}// for y
//cv::dft(complexImg, complexImg);
complexImage.ForwardFourierTransform();
// Calc Log AmpliTude of magnitude
double[,] logAmpl = new double[64, 64];
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
//Calculating elementwise complex conjugate of the shifted image 2d vector
logAmpl[x, y] = Math.Log(Complex.Multiply(
complexImage.Data[x, y], complexImage.Data[x, y]).Magnitude);
}
}// for y
Bitmap logAmp = logAmpl.ToBitmap();
// extract Phase, int[,] array = new int[4, 2];
double[,] myPhase = new double[64, 64];
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
//Calculating elementwise complex conjugate of the shifted image 2d vector
myPhase[x, y] = complexImage.Data[x, y].Phase;
}
}// for y
// calc Spectral Residual -------------------------
// logAmp smoothing
Accord.Imaging.Filters.FastBoxBlur filtBox =
new Accord.Imaging.Filters.FastBoxBlur(3, 3);
// apply the filter
Bitmap smoothAmp= filtBox.Apply(logAmp);
// subtraction
AForge.Imaging.Filters.Subtract filter =
new AForge.Imaging.Filters.Subtract(smoothAmp);
// apply the filter
Bitmap specResi = filter.Apply(logAmp);
// Calc Saliency map -----------------
// residual for Re
AForge.Imaging.ComplexImage totalSpec =
AForge.Imaging.ComplexImage.FromBitmap(specResi);
// + j*im
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
totalSpec.Data[x, y].Im = myPhase[x, y];
}
}// for y
// exp of re + j*im
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
totalSpec.Data[x, y] = Complex.Exp(totalSpec.Data[x, y]);
}
}// for y
// ifft2
//complexImage.ForwardFourierTransform();
totalSpec.ForwardFourierTransform();
// .^2 of ifft2
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
totalSpec.Data[x, y] =
Complex.Multiply(totalSpec.Data[x, y], totalSpec.Data[x, y]);
}
}// for y
// abs .^2
Bitmap salMap= totalSpec.ToBitmap();
// 가우시안 블러
Accord.Imaging.Filters.GaussianBlur filt2 =
new Accord.Imaging.Filters.GaussianBlur(2.5, 9);
// apply the filter
filt2.ApplyInPlace(salMap);
// create filter
Accord.Imaging.Filters.ContrastStretch filtNorm =
new Accord.Imaging.Filters.ContrastStretch();
// process image
filtNorm.ApplyInPlace(salMap);
//ImageBox.Show(salMap);
pictureBox3.Image = salMap;
What;s wrong with me?

3x3 Average filter in C#

I've written code to smooth an image,it's using 3x3 averaging filter. But seem it's not working
The picture output almost black
public void Smooth(Bitmap bmpInput){
Bitmap temp;
Color c;
float sum = 0;
for (int i = 0; i < bmpInput.Width; i++)
{
for (int j = 0; j < bmpInput.Height; j++)
{
c = bmpInput.GetPixel(i, j);
byte gray = (byte)(.333 * c.R + .333 * c.G + .333 * c.B);
bmpInput.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
}
}
temp = bmpInput;
for (int i = 0; i <= bmpInput.Width - 3; i++)
for (int j = 0; j <= bmpInput.Height - 3; j++)
{
for (int x = i; x <= i + 2; x++)
for (int y = j; y <= j + 2; y++)
{
c = bmpInput.GetPixel(x,y);
sum = sum + c.R ;
}
int color = (int)Math.Round(sum/9,10);
temp.SetPixel(i + 1, j + 1, Color.FromArgb(color, color, color));
sum = 0;
}
bmpInput = temp;
}
The variable tempstill refers to the exact same bitmap. You have to assign tempto new Bitmap image and work with this. Alternatively, you can store the new pixel values in a temporary array and transfer the contents of this array back to the image afterwards.

Rotating matrices

Objectives
Imagine that, we have matrix like
a11 a12 a13
a21 a22 a23
a31 a32 a33
What I want to do is, from textbox value rotate this matrix so that, for example if I write 2 and press rotate, program must keep both diagonal values of matrix (in this case a11, a22, a33, a13, a31) and rotate 2 times clockwise other values. So result must be like
a11 a32 a13
a23 a22 a21
a31 a12 a33
It must work for all N x N size matrices, and as you see every 4 rotation takes matrix into default state.
What I've done
So idea is like that, I have 2 forms. First takes size of matrix (1 value, for example if it's 5, it generates 5x5 matrix). When I press OK it generates second forms textbox matrix like that
Form 1 code
private void button1_Click(object sender, EventArgs e)
{
int matrixSize;
matrixSize = int.Parse(textBox1.Text);
Form2 form2 = new Form2(matrixSize);
form2.Width = matrixSize * 50 + 100;
form2.Height = matrixSize *60 + 200;
form2.Show();
//this.Hide();
}
Form 2 code generates textbox matrix from given value and puts random values into this fields
public Form2(int matrSize)
{
int counter = 0;
InitializeComponent();
TextBox[] MatrixNodes = new TextBox[matrSize*matrSize];
Random r = new Random();
for (int i = 1; i <= matrSize; i++)
{
for (int j = 1; j <= matrSize; j++)
{
var tb = new TextBox();
int num = r.Next(1, 1000);
MatrixNodes[counter] = tb;
tb.Name = string.Format("Node_{0}{1}", i, j);
Debug.Write(string.Format("Node_{0}{1}", i, j));
tb.Text = num.ToString();
tb.Location = new Point(j * 50, i * 50);
tb.Width = 30;
tb.Visible = true;
this.splitContainer1.Panel2.Controls.Add(tb);
counter++;
}
}
}
Form 2 has 1 textbox for controlling rotation (others are generated on the fly, programmatically). What I want to do is, when I enter rotation count and press Enter on this textbox, I want to rotate textbox matrix as I explained above. Can't figure out how to do it.
Copy both diagonals to separate arrays, then rotate your matrix and replace diagonals. Below code shows each step:
class Program
{
static void Main(string[] args)
{
int matrixSize = 3;
string[,] matrix = new string[matrixSize,matrixSize];
//create square matrix
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
matrix[x, y] = "a" + (x + 1).ToString() + (y + 1).ToString();
}
}
Console.WriteLine(Environment.NewLine + "Base square matrix");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(matrix[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//copy diagonals
string[] leftDiagonal = new string[matrixSize];
string[] rightDiagonal = new string[matrixSize];
for (int x = 0; x < matrixSize; x++)
{
leftDiagonal[x] = matrix[x, x];
rightDiagonal[x] = matrix[matrixSize - 1 - x, x];
}
Console.WriteLine(Environment.NewLine + "Diagonals");
for (int x = 0; x < matrixSize; ++x)
{
Console.Write(leftDiagonal[x] + " " + rightDiagonal[x] + Environment.NewLine);
}
Console.ReadKey();
//rotate matrix
string[,] rotatedMatrix = new string[matrixSize, matrixSize];
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
rotatedMatrix[x, y] = matrix[matrixSize - y - 1, x];
}
}
Console.WriteLine(Environment.NewLine + "Rotated");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrix[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//rotate matrix again
string[,] rotatedMatrixAgain = new string[matrixSize, matrixSize];
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
rotatedMatrixAgain[x, y] = rotatedMatrix[matrixSize - y - 1, x];
}
}
Console.WriteLine(Environment.NewLine + "Rotated again");
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrixAgain[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
//replace diagonals
for (int x = 0; x < matrixSize; x++)
{
rotatedMatrixAgain[x, x] = leftDiagonal[x];
rotatedMatrixAgain[matrixSize - 1 - x, x] = rightDiagonal[x];
}
Console.WriteLine(Environment.NewLine + "Completed" + Environment.NewLine);
for (int x = 0; x < matrixSize; x++)
{
for (int y = 0; y < matrixSize; y++)
{
Console.Write(rotatedMatrixAgain[x, y] + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
}
}
I don't know C#, so I can only give a suggestion in pseudocode:
Input: An N by N matrix in
Output: The input matrix rotated as described in the OP out
for i = 1 to N
for j = 1 to N
if N - j != i and i != j // Do not change values on either diagonal
out[j][N-i] = in[i][j]
else
out[i][j] = in[i][j]
Disclaimer: This algorithm is untested. I suggest you use a debugger to check that it works as you want.
This seems like quite an unorthodox UI presentation, but you're not too far off in terms of being able to achieve your functionality. Instead of a linear array, a rectangular array will make your job much easier. The actual rotation could be implemented with a for loop repeating a single rotation (which would be implemented as in the case 1 code), but I've decided to combine them into the four possible cases. This actually allows you to enter a negative number for number of rotations. Which reminds me, you really should do more error checking. At least protect against int.Parse throwing an exception both places it's used (with a try catch block or by switching to int.TryParse) and make sure it returns a meaningful number (greater than 0, possibly set a reasonable maximum other than int.MaxValue) for matrixSize in button1_Click.
namespace RotatingMatrices
{
public class Form2 : Form
{
// note these class fields
private TextBox[,] matrixNodes;
private int matrixSize;
public Form2(int matrSize)
{
InitializeComponent();
// note these inits
matrixSize = matrSize;
matrixNodes = new TextBox[matrixSize, matrixSize];
Random r = new Random();
// note the new loop limits
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
var tb = new TextBox();
int num = r.Next(1, 1000);
// note the change in indexing
matrixNodes[i,j] = tb;
tb.Name = string.Format("Node_{0}_{1}", i, j);
Debug.Write(string.Format("Node_{0}_{1}", i, j));
tb.Text = num.ToString();
tb.Location = new Point(j * 50, i * 50);
tb.Width = 30;
tb.Visible = true;
this.splitContainer1.Panel2.Controls.Add(tb);
}
}
}
private void buttonRotate_Click(object sender, EventArgs e)
{
string[,] matrix = new string[matrixSize, matrixSize];
int rotations = (4 + int.Parse(textBoxRotations.Text)) % 4; // note the addition of and mod by 4
switch(rotations)
{
case 1: // rotate clockwise
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[j, matrixSize - i - 1] = matrixNodes[i, j].Text;
}
}
break;
case 2: // rotate 180 degrees
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[i, j] = matrixNodes[matrixSize - i - 1, matrixSize - j - 1].Text;
}
}
break;
case 3: // rotate counter-clockwise
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrix[i, j] = matrixNodes[j, matrixSize - i - 1].Text;
}
}
break;
default: // do nothing
return;
}
// restore diagonals
for(int i = 0; i < matrixSize; i++)
{
matrix[i, i] = matrixNodes[i, i].Text;
matrix[i, matrixSize - i - 1] = matrixNodes[i, matrixSize - i - 1].Text;
}
// write strings back to text boxes
for (int i = 0; i < matrixSize; i++)
{
for (int j = 0; j < matrixSize; j++)
{
matrixNodes[i, j].Text = matrix[i, j];
}
}
}
}
}
I decided to tackle the issue using a listView instead of a text box, which makes the logic easier for me. Using this method, I was able to think of the matrix as successive boxes. I start on the outside and move in toward the middle, changing the size of my box each time.
Also, rather than using two forms, I use one. At the top I have a textbox where the user enters the size they want the array to be, and a button labeled "Fill" (button2). And at the bottom I have a textbox where the user enters the degree of rotation. When they click "Rotate," it kicks off a process of adding values to linked lists, combining and shifting the list, and then writing back out to the matrix. I'm sure I made it more convoluted than it has to be, but it was a great learning exercise.
After looking over jerry's code above, I think I'm going to look into rectangular arrays. :)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Recycle
{
public partial class Form1 : Form
{
public int size;
public LinkedList<string> topRight = new LinkedList<string>();
public LinkedList<string> bottomLeft = new LinkedList<string>();
public LinkedList<string> myMatrix = new LinkedList<string>();
public LinkedList<string> shiftMatrix = new LinkedList<string>();
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
listView1.Clear();
size = int.Parse(textBox2.Text);
int c = 0;
int q = 0;
int w = 0;
string[] content = new string[size];
Random rnd = new Random();
for (c = 0; c < size; c++)
{
listView1.Columns.Add("", 25);
}
for (q = 0; q < size; q++)
{
for (w = 0; w < size; w++)
{
content[w] = rnd.Next(9,100).ToString();
}
ListViewItem lvi = new ListViewItem(content);
listView1.Items.Add(lvi);
}
}
public bool iseven(int size)
{
if (size % 2 == 0)
{
return true;
}
else
{
return false;
}
}
public void button1_Click(object sender, EventArgs e)
{
if (listView1.Items.Count < 3)
{
MessageBox.Show("Matrix cannot be rotated.");
return;
}
bool even = false;
int shift = int.Parse(textBox1.Text); //amount to shift by
int box = listView1.Items.Count - 1; //size of box
int half = Convert.ToInt32(listView1.Items.Count / 2);
int corner = 0; //inside corner of box
if (shift > listView1.Items.Count)
{
shift = shift % ((listView1.Items.Count - 2) * 4);
}
do
{
eachPass(shift, box, corner);
++corner;
--box;
} while (box >= half + 1);
}
public void eachPass(int shift, int box, int corner)
{
int x;
int i;
//Read each non-diagonal value into one of two lists
for (x = corner + 1; x < box; x++)
{
topRight.AddLast(listView1.Items[corner].SubItems[x].Text);
}
x = box;
for (i = corner + 1; i < box; i++)
{
topRight.AddLast(listView1.Items[i].SubItems[x].Text);
}
for (x = box - 1; x > corner; x--)
{
bottomLeft.AddLast(listView1.Items[box].SubItems[x].Text);
}
x = corner;
for (i = box - 1; i > corner; i--)
{
bottomLeft.AddLast(listView1.Items[i].SubItems[x].Text);
}
string myTest = "";
//join the two lists, so they can be shifted
foreach (string tR in topRight)
{
myMatrix.AddLast(tR);
}
foreach (string bL in bottomLeft)
{
myMatrix.AddLast(bL);
}
int sh;
//shift the list using another list
for (sh = shift; sh < myMatrix.Count; sh++)
{
shiftMatrix.AddLast(myMatrix.ElementAt(sh));
}
for (sh = 0; sh < shift; sh++)
{
shiftMatrix.AddLast(myMatrix.ElementAt(sh));
}
//we need the sizes of the current lists
int trCnt = topRight.Count;
int blCnt = bottomLeft.Count;
//clear them for reuse
topRight.Clear();
bottomLeft.Clear();
int s;
//put the shifted values back
for (s = 0; s < trCnt; s++)
{
topRight.AddLast(shiftMatrix.ElementAt(s));
}
for (s = blCnt; s < shiftMatrix.Count; s++)
{
bottomLeft.AddLast(shiftMatrix.ElementAt(s));
}
int tRn = 0;
int bLn = 0;
//write each non-diagonal value from one of two lists
for (x = corner + 1; x < box; x++)
{
listView1.Items[corner].SubItems[x].Text = topRight.ElementAt(tRn);
++tRn;
}
x = box;
for (i = corner + 1; i < box; i++)
{
listView1.Items[i].SubItems[x].Text = topRight.ElementAt(tRn);
++tRn;
}
for (x = box - 1; x > corner; x--)
{
listView1.Items[box].SubItems[x].Text = bottomLeft.ElementAt(bLn);
++bLn;
}
x = corner;
for (i = box - 1; i > corner; i--)
{
listView1.Items[i].SubItems[x].Text = bottomLeft.ElementAt(bLn);
++bLn;
}
myMatrix.Clear();
shiftMatrix.Clear();
topRight.Clear();
bottomLeft.Clear();
}
}
}

Populating a color array with every 8th pixel in an image. C#

I have an image that is 512x280 pixels. I want to populate a 64x35 array with every 8th pixel in the matrix.
Here is what I have right now:
Color[,] imgArray = new Color[b.Width, b.Height];
for (int y = 0; y < 35; y++)
{
for (int x = 0; x < 64; x++)
{
imgArray[x, y] = b.GetPixel(x, y);
}
}
But that will get just the top corner of the image. How would I change the loop so it grabs every 8th pixel to fill the array with?
edit: I think I may have gotten it. Can someone read this and assure me that it is correct?
Color[,] imgArray = new Color[64, 35];
for (int y = 0; y < 280; y+=8)
{
for (int x = 0; x < 512; x+=8)
{
imgArray[x, y] = b.GetPixel(x, y);
}
}
Simply multiply the coordinates by 8 when you get the pixels:
Color[,] imgArray = new Color[64, 35];
for (int y = 0; y < 35; y++) {
for (int x = 0; x < 64; x++) {
imgArray[x, y] = b.GetPixel(x * 8, y * 8);
}
}

Categories