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()
相关推荐
xueyongfu2 分钟前
从Diffusion到VLA pi0(π0)
人工智能·算法·stable diffusion
爱装代码的小瓶子6 分钟前
【c++进阶】从C++98到C++11的奇妙旅程(故事科普版)
开发语言·c++
智航GIS9 分钟前
2.3 运算符详解
开发语言·python
屋顶那猫9 分钟前
使用pyinstaller打包pytest项目
python·pytest
web3.088899913 分钟前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
jackylzh18 分钟前
配置pytorch环境,并调试YOLO
人工智能·pytorch·yolo
刹那间的回眸x.y19 分钟前
UnitTestReport挺好用
python
杜子不疼.26 分钟前
AI Ping双款新模型同步免费解锁:GLM-4.7与MiniMax M2.1实测
人工智能
打码人的日常分享27 分钟前
企业数据资产管控和数据治理解决方案
大数据·运维·网络·人工智能·云计算
百***787528 分钟前
小米MiMo-V2-Flash深度解析:国产开源大模型标杆与海外AI接入方案
人工智能·开源