Chocolade19721309

Untitled

Jun 27th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. using OpenCvSharp;
  9. using OpenCvSharp.Extensions;
  10.  
  11. namespace ImageCoordinateMapper
  12. {
  13. public class SegmentAnalyzer
  14. {
  15. private List<System.Drawing.Point> _pointsOnImage;
  16. private Bitmap bmp;
  17.  
  18. public SegmentAnalyzer(List<System.Drawing.Point> pointsOnImage, Bitmap bitmap)
  19. {
  20. _pointsOnImage = pointsOnImage;
  21. bmp = bitmap;
  22. }
  23.  
  24. public int CalculateSquareSize()
  25. {
  26. var mostLeftPoint = _pointsOnImage.Min(p => p.X);
  27. var mostRightPoint = _pointsOnImage.Max(p => p.X);
  28. int baseWidth = mostRightPoint - mostLeftPoint;
  29. return (int)(0.03 * baseWidth); // Adjust the fraction if necessary
  30. }
  31.  
  32. public double CalculateGrayLevelAverage(Rectangle square)
  33. {
  34. double sumGrayLevels = 0;
  35. int pixelCount = 0;
  36.  
  37. for (int y = square.Top; y < square.Bottom; y++)
  38. {
  39. for (int x = square.Left; x < square.Right; x++)
  40. {
  41. Color pixelColor = bmp.GetPixel(x, y);
  42. double grayLevel = (pixelColor.R + pixelColor.G + pixelColor.B) / 3.0;
  43. sumGrayLevels += grayLevel;
  44. pixelCount++;
  45. }
  46. }
  47.  
  48. return sumGrayLevels / pixelCount;
  49. }
  50.  
  51. public async Task GenerateCsvFileAsync(int totalFrames, VideoCapture videoCapture, string outputFilePath, IProgress<int> progress)
  52. {
  53. int squareSize = CalculateSquareSize();
  54. using (StreamWriter writer = new StreamWriter(outputFilePath))
  55. {
  56. await writer.WriteLineAsync("FRAME_NUMBER,MINUS,LEFTDIGIT_TOP,LEFTDIGIT_LEFTTOP,...,RIGHTDIGIT_RIGHTBOTTOM,RIGHTDIGIT_BOTTOM");
  57.  
  58. for (int frameNumber = 0; frameNumber < totalFrames; frameNumber++)
  59. {
  60. videoCapture.Set(VideoCaptureProperties.PosFrames, frameNumber);
  61. Mat frame = new Mat();
  62. if (videoCapture.Read(frame))
  63. {
  64. Bitmap bitmap = BitmapConverter.ToBitmap(frame);
  65. bmp = bitmap;
  66. string line = $"{frameNumber}";
  67.  
  68. foreach (var point in _pointsOnImage)
  69. {
  70. Rectangle square = new Rectangle(point.X - squareSize / 2, point.Y - squareSize / 2, squareSize, squareSize);
  71. double grayLevelAverage = CalculateGrayLevelAverage(square);
  72. line += $",{grayLevelAverage}";
  73. }
  74.  
  75. await writer.WriteLineAsync(line);
  76. }
  77. progress?.Report(frameNumber);
  78. }
  79. }
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment