Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using OpenCvSharp;
- using OpenCvSharp.Extensions;
- namespace ImageCoordinateMapper
- {
- public class SegmentAnalyzer
- {
- private List<System.Drawing.Point> _pointsOnImage;
- private Bitmap bmp;
- public SegmentAnalyzer(List<System.Drawing.Point> pointsOnImage, Bitmap bitmap)
- {
- _pointsOnImage = pointsOnImage;
- bmp = bitmap;
- }
- public int CalculateSquareSize()
- {
- var mostLeftPoint = _pointsOnImage.Min(p => p.X);
- var mostRightPoint = _pointsOnImage.Max(p => p.X);
- int baseWidth = mostRightPoint - mostLeftPoint;
- return (int)(0.03 * baseWidth); // Adjust the fraction if necessary
- }
- public double CalculateGrayLevelAverage(Rectangle square)
- {
- double sumGrayLevels = 0;
- int pixelCount = 0;
- for (int y = square.Top; y < square.Bottom; y++)
- {
- for (int x = square.Left; x < square.Right; x++)
- {
- Color pixelColor = bmp.GetPixel(x, y);
- double grayLevel = (pixelColor.R + pixelColor.G + pixelColor.B) / 3.0;
- sumGrayLevels += grayLevel;
- pixelCount++;
- }
- }
- return sumGrayLevels / pixelCount;
- }
- public async Task GenerateCsvFileAsync(int totalFrames, VideoCapture videoCapture, string outputFilePath, IProgress<int> progress)
- {
- int squareSize = CalculateSquareSize();
- using (StreamWriter writer = new StreamWriter(outputFilePath))
- {
- await writer.WriteLineAsync("FRAME_NUMBER,MINUS,LEFTDIGIT_TOP,LEFTDIGIT_LEFTTOP,...,RIGHTDIGIT_RIGHTBOTTOM,RIGHTDIGIT_BOTTOM");
- for (int frameNumber = 0; frameNumber < totalFrames; frameNumber++)
- {
- videoCapture.Set(VideoCaptureProperties.PosFrames, frameNumber);
- Mat frame = new Mat();
- if (videoCapture.Read(frame))
- {
- Bitmap bitmap = BitmapConverter.ToBitmap(frame);
- bmp = bitmap;
- string line = $"{frameNumber}";
- foreach (var point in _pointsOnImage)
- {
- Rectangle square = new Rectangle(point.X - squareSize / 2, point.Y - squareSize / 2, squareSize, squareSize);
- double grayLevelAverage = CalculateGrayLevelAverage(square);
- line += $",{grayLevelAverage}";
- }
- await writer.WriteLineAsync(line);
- }
- progress?.Report(frameNumber);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment