昨天玩了下AI,发现让AI写代码真的是比我自己写得好,于是拿出工作中遇到的工业视觉中,visionpro的图像旋转后坐标系变化的问题问它。我只能说句确实牛逼,还给了我多种解决办法,虽然都是visionpro9.0以上的方法。最后从它嘴里套出了两种C#实现图像翻转或者旋转180°坐标系不变化的方法。
首先看看使用visionpro图像处理工具进行翻转旋转后的效果。
很明显,图像坐标系也跟着转了,也就是图像坐标系原点跟着转到了右下角。
使用C#的方法实现,问了AI,它说不会对图像精度造成影响,可以放心使用。
复制
Bitmap imgflipped() {
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// 加载图像
Bitmap bitmap = new Bitmap(@"C:\Users\daimadog\Desktop\19.png");
// 获取图像的宽度和高度
int width = bitmap.Width;
int height = bitmap.Height;
// 创建新的Bitmap对象
Bitmap flippedBitmap = new Bitmap(width, height);
// 循环遍历每一个像素,并进行翻转
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color color = bitmap.GetPixel(x, y);
flippedBitmap.SetPixel(x, height - y - 1, color);
}
}
stopwatch.Stop();
Console.WriteLine($"程序运行耗时:{stopwatch.ElapsedMilliseconds}毫秒");
return flippedBitmap;
}结果如上图所示,可以从找到的几个点坐标中看出,图像确实被旋转了,而且坐标系没有变化,是我想要的功能,就是性能方面有点尴尬。
程序运行耗时:5603毫秒
于是我又让它给了一段性能优化后的代码,此代码需要在visual studio的项目属性的生成选项中开启不安全代码编译。
复制
Bitmap imgflipped() {
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// 加载图像
Bitmap bitmap = new Bitmap(@"C:\Users\daimadog\Desktop\19.png");
// 获取图像的宽度和高度
int width = bitmap.Width;
int height = bitmap.Height;
// 创建新的Bitmap对象
Bitmap flippedBitmap = new Bitmap(width, height);
// 锁定原始图像的像素数据
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
IntPtr bitmapDataPtr = bitmapData.Scan0;
int stride = bitmapData.Stride;
// 锁定新的Bitmap对象的像素数据
BitmapData flippedBitmapData = flippedBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
IntPtr flippedBitmapDataPtr = flippedBitmapData.Scan0;
// 循环遍历每一行的像素数据,并进行翻转
unsafe
{
byte* bitmapDataBytePtr = (byte*)bitmapDataPtr.ToPointer();
byte* flippedBitmapDataBytePtr = (byte*)flippedBitmapDataPtr.ToPointer();
for (int y = 0; y < height; y++)
{
byte* bitmapDataRowPtr = bitmapDataBytePtr + y * stride;
byte* flippedBitmapDataRowPtr = flippedBitmapDataBytePtr + (height - y - 1) * stride;
for (int x = 0; x < width * 3; x++)
{
flippedBitmapDataRowPtr[x] = bitmapDataRowPtr[x];
}
}
}
// 解锁像素数据
bitmap.UnlockBits(bitmapData);
flippedBitmap.UnlockBits(flippedBitmapData);
stopwatch.Stop();
Console.WriteLine($"程序运行耗时:{stopwatch.ElapsedMilliseconds}毫秒");
return flippedBitmap;
}返回的图像和上图一样,程序运行耗时:117毫秒,虽然不及visionpro,但也算是可以使用了。







评论 (0)