teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コメントを受け変換部追記。

2020/01/13 03:03

投稿

退会済みユーザー
answer CHANGED
@@ -17,4 +17,67 @@
17
17
  それが出来たらOpenCVでK-meansしてください。
18
18
  それが出来て初めて24bitから8bitへの変換です。とりあえずパレットとはどういうものかについて調べてみて良く分からなかったらまたコメントください。
19
19
 
20
- あと、質問を編集しただけでは私には通知が来ないようなので回答にコメントしてもらえると反応が早いかもしれません。
20
+ あと、質問を編集しただけでは私には通知が来ないようなので回答にコメントしてもらえると反応が早いかもしれません。
21
+
22
+ 【コメントを受け追記】
23
+ 減色済みの奴が対象で減勘だけするならこんな感じで良いはず。
24
+ 例外処理とか諸々省略してるので注意。
25
+ ```C#
26
+ static Bitmap ImageConvert24bitTo8bit(Bitmap bmpSource)
27
+ {
28
+ Bitmap bmp8bit = new Bitmap(bmpSource.Width, bmpSource.Height, PixelFormat.Format8bppIndexed);
29
+
30
+ BitmapData bmpData8bit = bmp8bit.LockBits(
31
+ new Rectangle(0, 0, bmp8bit.Width, bmp8bit.Height),
32
+ ImageLockMode.WriteOnly,
33
+ bmp8bit.PixelFormat
34
+ );
35
+
36
+ BitmapData bmpData24bit = bmpSource.LockBits(
37
+ new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
38
+ ImageLockMode.ReadOnly,
39
+ bmpSource.PixelFormat
40
+ );
41
+
42
+ byte[] imgBuf8bit = new byte[bmpData8bit.Stride * bmp8bit.Height];
43
+ byte[] imgBuf24bit = new byte[bmpData24bit.Stride * bmpSource.Height];
44
+
45
+ Marshal.Copy(bmpData24bit.Scan0, imgBuf24bit, 0, imgBuf24bit.Length);
46
+
47
+ var colors = new Dictionary<Color, byte>();
48
+ byte colorIndex = 0;
49
+
50
+ for (int y = 0; y < bmpSource.Height; y++)
51
+ {
52
+ for (int x = 0; x < bmpSource.Width; x++)
53
+ {
54
+ int index24bit = y * bmpData24bit.Stride + x * 3;
55
+ int index8bit = y * bmpData8bit.Stride + x;
56
+ byte b = imgBuf24bit[index24bit];
57
+ byte g = imgBuf24bit[index24bit + 1];
58
+ byte r = imgBuf24bit[index24bit + 2];
59
+
60
+ // 24bitから8bitへ
61
+ var color = Color.FromArgb(r, g, b);
62
+ if (colors.TryGetValue(color, out byte i))
63
+ imgBuf8bit[index8bit] = i;
64
+ else
65
+ {
66
+ imgBuf8bit[index8bit] = colorIndex;
67
+ colors.Add(color, colorIndex);
68
+ colorIndex++;
69
+ }
70
+ }
71
+ }
72
+ Marshal.Copy(imgBuf8bit, 0, bmpData8bit.Scan0, imgBuf8bit.Length);
73
+ bmpSource.UnlockBits(bmpData24bit);
74
+ bmp8bit.UnlockBits(bmpData8bit);
75
+
76
+ var pal = bmp8bit.Palette;
77
+ foreach (var item in colors)
78
+ pal.Entries[item.Value] = item.Key;
79
+ bmp8bit.Palette = pal;
80
+
81
+ return bmp8bit;
82
+ }
83
+ ```