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()
相关推荐
tianyuanwo几秒前
Python 属性查找陷阱:从 `AttributeError: ‘X‘ object has no attribute ‘_children‘` 说起
python
yichengerp1 分钟前
国内中小电子工厂用哪个erp系统好?
大数据·运维·人工智能·云计算·制造
q27551300422 分钟前
微纳代理 WN8034F 国产降噪音频方案
人工智能·语音识别
喜欢打篮球的普通人6 分钟前
MiniMind 学习笔记(二十二):数学 Cookbook——把概率空间、期望、似然一次讲明白
人工智能·笔记·学习
程序猿阿森8 分钟前
混合精度详解:FP16 vs BF16,Loss Scaling 与 PyTorch 实战
人工智能·pytorch·python
Lazionr8 分钟前
unordered_map和unordered_set的使用
开发语言·c++·算法
ADark9 分钟前
FDE 入门 · 08|没人爱做的交付尾巴
人工智能·agent
alonglong9 分钟前
macOS 定时任务排错:退出码、错误消息、旧结论,三个都不承载事实
人工智能
benchmark_cc9 分钟前
A股、港股、美股日K如何拼接?处理不同交易日造成的时间轴错位
大数据·python·pandas·量化交易·股票数据·quantdash
招财牛猫12 分钟前
从文本生成到校准决策:Jev 的技术路线解析
人工智能