我有一个包含一系列jpg的文件夹,这些jpg是视频帧转换成的。我编写了一些代码来遍历它们并显示它们。
我正在尝试从C#中的JPG图像上绘制一个绿色框。高度、宽度、XC和YC在XML中,我只需访问每个框架的数据即可。我使用位图使其正常工作,但是为了在WPF中显示它,我必须首先将其转换为位图图像。问题是这需要太长时间。我希望视频以25 fps播放。因此,所有处理都需要在40毫秒内完成。目前,显示新图像需要花费0.01到0.3秒不等的时间。
以下是我目前拥有的代码-
绘制矩形边框方法 -
我正在尝试从C#中的JPG图像上绘制一个绿色框。高度、宽度、XC和YC在XML中,我只需访问每个框架的数据即可。我使用位图使其正常工作,但是为了在WPF中显示它,我必须首先将其转换为位图图像。问题是这需要太长时间。我希望视频以25 fps播放。因此,所有处理都需要在40毫秒内完成。目前,显示新图像需要花费0.01到0.3秒不等的时间。
以下是我目前拥有的代码-
public void UpdateImage(string imageName, int[] boxData)
{
// imageName is the file path the image
Bitmap oldImage = new Bitmap(imageName);
// if objects are detected
if (boxData.Length != 0)
{
// transforms x and y cords to align box better to light
int newXC = boxData[0] - (boxData[2] / 2);
int newYC = boxData[1] - (boxData[3] / 2);
// ensures cords are not negative
if (newXC < 0)
newXC = 0;
if (newYC < 0)
newYC = 0;
// uses the DrawRectangleBorder to draw rectangles
Bitmap newImage = DrawRectangleBorder(oldImage, new Rectangle(new System.Drawing.Point(newXC, newYC), new System.Drawing.Size(boxData[2], boxData[3])), Color.Green);
// converts Bitmap to BitmapImage
using (MemoryStream memory = new MemoryStream())
{
newImage.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
ImportImage.Source = bitmapImage;
}
}
else
{
Bitmap newImage = oldImage;
// converts Bitmap to BitmapImage
using (MemoryStream memory = new MemoryStream())
{
newImage.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
ImportImage.Source = bitmapImage;
}
}
}
绘制矩形边框方法 -
private static Bitmap DrawRectangleBorder(Bitmap image, Rectangle rectangle, Color colour)
{
// makes new blank Bitmap from the old ones width and height
Bitmap newBitmap = new Bitmap(image.Width, image.Height);
// opens up the blank bit
using (Graphics graphics = Graphics.FromImage(newBitmap))
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
// what actually draws the rectangles
for (Int32 x = rectangle.Location.X; x <= rectangle.Right && x < image.Width; x++)
for (Int32 y = rectangle.Location.Y; y <= rectangle.Bottom && y < image.Height; y++)
if (y == rectangle.Location.Y || y == rectangle.Bottom || x == rectangle.Location.X || x == rectangle.Right)
newBitmap.SetPixel(x, y, colour);
return newBitmap;
}
以下是其中一张图片的样子,它们的分辨率为640x480 - [1]: https://istack.dev59.com/ZiocC.webp 希望这能有所帮助!