pythonnet python图像 C# .NET图像 互转

C#是dotnet的代表虽然不是一个东西但是在这里代表同一件事,不要在意细节。

pythonnet是 python 和.net无缝连接的桥梁。那么python的图像是numpy表示,C#图象是Bitmap。

做图像想要python的便利又想要dotnet的强大就需要图像类型转换。

上程序。

1.Bitmap_转opencv-python

python 复制代码
import clr
import numpy as np
import cv2
from System.IO import MemoryStream
clr.AddReference('System.Drawing')
from System.Drawing import Bitmap

# 确保已经加载了System.Drawing程序集


# 假设你已经有了一个Bitmap对象
# 例如,从文件加载一个Bitmap对象
bitmap = Bitmap("8.bmp")

# 将Bitmap转换为字节数组
def bitmap_to_bytes(bitmap):
    stream = MemoryStream()
    bitmap.Save(stream, bitmap.RawFormat)  # 保存图像到流中
    stream.Position = 0  # 重置流的位置
    return np.frombuffer(stream.ToArray(), dtype=np.uint8)

bitmap_data = bitmap_to_bytes(bitmap)

# 使用OpenCV的imdecode函数将字节数组解码为Mat对象
mat = cv2.imdecode(bitmap_data, cv2.IMREAD_COLOR)

# 现在你可以使用OpenCV的功能处理这个Mat对象了
# 例如,将其转换为灰度图像
gray_mat = cv2.cvtColor(mat, cv2.COLOR_BGR2GRAY)

# 显示图像
cv2.imshow("Gray Image", gray_mat)
cv2.imshow("GrImage", mat)
cv2.waitKey(0)
cv2.destroyAllWindows()

2.numpy转bitmap

python 复制代码
import clr
import numpy as np
import cv2
from System.IO import MemoryStream

clr.AddReference('System.Drawing')
from System.Drawing import Bitmap, Imaging

# 读取图像(确保路径正确)
image_path = "Lena.png"
cv_image = cv2.imread(image_path)

# 将BGR格式转换为RGB格式
cv_image_rgb = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)

# 创建一个与图像数据相匹配的numpy数组
h, w, c = cv_image_rgb.shape
numpy_array = np.array(cv_image_rgb, dtype=np.uint8).reshape((h, w, c))

# 创建一个MemoryStream对象并将numpy数组写入
stream = MemoryStream()
cv2.imencode('.png', numpy_array)[1].tobytes()
stream.Write(cv2.imencode('.png', numpy_array)[1].tobytes(), 0, len(cv2.imencode('.png', numpy_array)[1].tobytes()))
stream.Position = 0

# 使用.NET的System.Drawing命名空间中的Bitmap类从MemoryStream创建Bitmap对象
bitmap = Bitmap.FromStream(stream)

# 现在你有一个System.Drawing.Bitmap对象,可以在.NET环境中使用
# 例如,保存到文件
bitmap.Save("output_image.png", Imaging.ImageFormat.Png)

# 清理资源
stream.Close()
相关推荐
小羊没烦恼!5 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
回眸&啤酒鸭5 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智5 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅5 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein5 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
LaughingZhu5 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化