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()
相关推荐
技能咖1 分钟前
探索AI新领域:生成式人工智能认证(GAI认证)助力职场发展
人工智能·职场和发展
为自己_带盐6 分钟前
浅聊一下数据库的索引优化
开发语言·数据库·php
Eric.Lee202110 分钟前
conda 输出指定python环境的库 输出为 yaml文件
linux·python·conda
音视频牛哥11 分钟前
灰度图像和RGB图像在数据大小和编码处理方式差别
人工智能·深度学习·计算机视觉·大牛直播sdk·灰度图像·灰度图像编码·rgb和灰度图像差别
Funny_AI_LAB12 分钟前
首个专业AI设计Agent发布-Lovart
人工智能·科技·ai
threelab12 分钟前
05.three官方示例+编辑器+AI快速学习three.js webgl - animation - skinning - ik
人工智能·学习·编辑器
threelab12 分钟前
04.three官方示例+编辑器+AI快速学习webgl_animation_skinning_additive_blending
人工智能·学习·编辑器
PAQQ15 分钟前
【python】windows实现与k230使用socket通信并传输文件
python·stm32·单片机
奇睿海16 分钟前
NLP的基本流程概述
人工智能·自然语言处理
深度学习机器学习16 分钟前
计算机视觉最不卷的方向:三维重建学习路线梳理
人工智能·深度学习·学习·yolo·目标检测·机器学习·计算机视觉