-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
244 lines (212 loc) · 9.25 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Threading;
using System.Threading.Tasks;
using NDesk.Options;
namespace ImageMosaicGenerator
{
internal static class Program
{
private static void Main(string[] args)
{
// Define variables for arguments
var showHelp = false;
var imagePath = "";
var tilesPath = "";
var tileSize = 0;
var imageSize = 0;
var threadCount = 0;
// Define arguments
var p = new OptionSet () {
{
"i|image=", "Path to the image",
v => imagePath = v
},
{
"t|tiles=", "Path to the folder containing tile images",
v => tilesPath = v
},
{
"s|tileSize=", "The size of individual tiles",
(int v) => tileSize = v
},
{
"w|imageSize=", "The size of the image in tiles",
(int v) => imageSize = v
},
{
"c|threads=", "The number of threads to use",
(int v) => threadCount = v
},
{
"h|help", "show this message and exit",
v => showHelp = v != null
},
};
// Parse arguments
List<string> extra;
try
{
extra = p.Parse(args);
}
catch (OptionException e)
{
Console.Write("Invalid Arguments: ");
Console.WriteLine(e.Message);
Console.WriteLine("Use `--help' for more information.");
return;
}
// Display help
if (showHelp)
{
ShowHelp(p);
return;
}
// Find all image files
var ext = new List<string> { ".jpg", ".png" };
var tileImages = Directory.GetFiles(tilesPath, "*.*", SearchOption.AllDirectories).Where(s => ext.Contains(Path.GetExtension(s))).ToArray();
// Define arrays objects to be shared between classes
var storage = new ThreadedStorage(tileImages, imagePath, tileSize);
var threadList = new Task[threadCount];
Console.WriteLine("Pricess Tiles");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Start the threads to process images
// This calculates the average color foe each pixel
for (var i = 0; i < threadCount; i++)
{
threadList[i] = Task.Factory.StartNew(() => ProcessTileImages(storage));
}
// Wait for the threads to finish
Task.WaitAll(threadList);
stopwatch.Stop();
Console.WriteLine("Elapsed time: " + stopwatch.ElapsedMilliseconds / 1000);
stopwatch.Restart();
Console.WriteLine("Pricess Image");
// Define the color queue
Queue<PixelColorAndPosition> ImageColorQueue;
int[] tiledImageSize;
// Calculate image size after scaling it down to tiles
using (Bitmap bm = new Bitmap(imagePath))
{
int smallestSide = Math.Min(bm.Width, bm.Height);
tiledImageSize = new int[2] { (int)Math.Round((float)bm.Width / smallestSide * imageSize), (int)Math.Round((float)bm.Height / smallestSide * imageSize) };
// Create the color queue to be used by the threads
// This stores the Image as a color array in a queue used for multi threading
using (Bitmap sBm = ImageProcessing.ResizeImage(bm, tiledImageSize[0], tiledImageSize[1]))
{
ImageColorQueue = new Queue<PixelColorAndPosition>(Misc.BitmapToColorList(sBm));
}
}
Bitmap finalImage = new Bitmap(tiledImageSize[0] * tileSize, tiledImageSize[1] * tileSize);
using (Graphics g = Graphics.FromImage(finalImage))
{
g.CompositingMode = CompositingMode.SourceCopy;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.SmoothingMode = SmoothingMode.None;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.PixelOffsetMode = PixelOffsetMode.HighSpeed;
// override the old thread array with an empty one
threadList = new Task[threadCount];
// Start the threads to process the image
// This picks the image for each pixel of the image
for (var i = 0; i < threadCount; i++)
{
threadList[i] = Task.Factory.StartNew(() => ProcessImage(storage, ref ImageColorQueue, g));
}
// Wait for the threads to finish
Task.WaitAll(threadList);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: " + stopwatch.ElapsedMilliseconds / 1000);
finalImage.Save("yeet.png");
}
/*
* This function shows the user how to use the program
*/
private static void ShowHelp(OptionSet p)
{
Console.WriteLine ("Usage: dotnet ImageMosaicGenerator.dll [OPTIONS]");
Console.WriteLine ("Convert the 'image' to a mosaic using 'tiles'");
Console.WriteLine ();
Console.WriteLine ("Options:");
p.WriteOptionDescriptions (Console.Out);
}
/*
* This function goes through all of the images and calculates their average color
*/
private static void ProcessTileImages(ThreadedStorage storage)
{
while (storage.ImagePathsQueue.Count > 0)
{
// Get next image to process
string pathToImage;
lock (storage.ImagePathsQueue)
{
pathToImage = storage.ImagePathsQueue.Dequeue();
}
// Verify an image got returned
if (pathToImage == null)
break;
// Run the code in a try loop in case something goes wrong
try
{
// Load the image
using var bm = new Bitmap(pathToImage);
// Square the image so it can be used as a single pixel
using var squareBm = ImageProcessing.SquareAndResizeImage(bm, storage.TileSize);
// This will throw an exception when there is something wrong with the bitmap
// There was an issue where SquareAndResizeImage() wouldnt throw an error and the return variable was corrupted
int test = squareBm.Width;
// Resize image
//using var resizedBm = ImageProcessing.ResizeImage(bm, storage.TileSize, storage.TileSize);
// Get the average color and convert to CIELAB
var imgCol = ColorConversion.RGBtoCIELAB(ImageProcessing.AverageImageColor(squareBm));
// Lock the array and save the result
lock (storage.TilesColors)
{
// Save the color in a shared array
storage.TilesColors.Add(new ImagePathColor(pathToImage, imgCol));
}
}
catch (Exception e)
{
Console.WriteLine(storage.ImagePathsQueue.Count + ". " + e.Message);
continue;
}
}
}
private static void ProcessImage(ThreadedStorage storage, ref Queue<PixelColorAndPosition> ImageColorQueue, Graphics g)
{
ImagePathColor[] localList = storage.TilesColors.ToArray();
while (ImageColorQueue.Count > 0)
{
// Get next pixel to process
PixelColorAndPosition pixel;
lock (ImageColorQueue)
{
pixel = ImageColorQueue.Dequeue();
}
// Get closest image
ImagePathColor pixelImage = Misc.FindClosesColor(pixel.color, localList);
// Draw image
using Bitmap bm = new Bitmap(pixelImage.ImagePath);
using Bitmap sBm = ImageProcessing.SquareImage(bm);
using Bitmap smallSBm = ImageProcessing.ResizeImage(sBm, storage.TileSize, storage.TileSize);
lock (g)
{
g.DrawImage(smallSBm, pixel.position[0] * storage.TileSize, pixel.position[1] * storage.TileSize, storage.TileSize, storage.TileSize);
//g.FillRectangle(new SolidBrush(ColorConversion.CIELABtoRGB(pixel.color)), pixel.position[0] * storage.TileSize, pixel.position[1] * storage.TileSize, storage.TileSize, storage.TileSize);
}
}
}
}
}