diff --git a/TIASshot/ColorCorrection/ColorCorrector.cs b/TIASshot/ColorCorrection/ColorCorrector.cs index c253291..eadebea 100644 --- a/TIASshot/ColorCorrection/ColorCorrector.cs +++ b/TIASshot/ColorCorrection/ColorCorrector.cs @@ -198,48 +198,21 @@ /// /// 8bit 画像 internal Mat ConvertImage(Mat src, Mat conv) { - // 1. 型変換: src を CV_64FC3 に変換(in-place) if (src.Type() != MatType.CV_64FC3) { src.ConvertTo(src, MatType.CV_64FC3); } + using (var flatten = src.Reshape(3, src.Height * src.Width)) + using (var extended = ExtendMat(flatten, conv.Rows)) + using (var converted = (extended * conv).ToMat()) + using (var convertedImage = converted.Reshape(3, src.Height)) { + //Clipping to 8bit range + //unsafe { + // convertedImage.ForEachAsVec3d(Clip8bit); + //} - // 2. Reshape: メモリ共有を避けるため Clone を使用 - Mat flatten = null; - Mat extended = null; - Mat matrixProduct = null; - Mat convertedImage = null; - Mat convImg8 = null; - - try { - // Reshape は元のメモリを共有するため、Clone で独立コピーを作成 - using (var flattenView = src.Reshape(3, src.Height * src.Width)) { - flatten = flattenView.Clone(); - } - - // 3. 行列拡張 - extended = ExtendMat(flatten, conv.Rows); - - // 4. 行列乗算: MatExpr の一時オブジェクトを避けるため、明示的に ToMat + Clone - using (var product = (extended * conv).ToMat()) { - matrixProduct = product.Clone(); - } - - // 5. Reshape: 再び Clone で安全化 - using (var convertedView = matrixProduct.Reshape(3, src.Height)) { - convertedImage = convertedView.Clone(); - } - - // 6. 8bit 変換 - convImg8 = new Mat(); + var convImg8 = new Mat(); convertedImage.ConvertTo(convImg8, MatType.CV_8UC3); - return convImg8; - } finally { - // 中間 Mat を確実に破棄(convImg8 は返り値なので破棄しない) - flatten?.Dispose(); - extended?.Dispose(); - matrixProduct?.Dispose(); - convertedImage?.Dispose(); } } @@ -251,9 +224,7 @@ internal Mat ExtendMat(Mat src, int channels) { if (src.Cols * src.Channels() != 3) return src; var dst = new Mat(src.Rows, channels, MatType.CV_64FC1); - // Parallel.For を通常の for ループに変更 - // Releaseモード最適化 + 低スペックPCでのスレッド競合を回避 - for (int row = 0; row < src.Rows; row++) { + Parallel.For(0, src.Rows, row => { var vals = new double[] { src.Cols == 1 ? src.At(row, 0)[2] : src.At(row, 2), // R src.Cols == 1 ? src.At(row, 0)[1] : src.At(row, 1), // G @@ -263,7 +234,7 @@ for (int i = 0; i < channels; i++) { dst.At(row, i) = vals[ExtendChannels[i][0]] * vals[ExtendChannels[i][1]] * vals[ExtendChannels[i][2]]; } - } + }); return dst; } }