中国建设教育协会官方网站查,整合营销策略,wordpress 支付,自己设置网站怎么做C#是dotnet的代表虽然不是一个东西但是在这里代表同一件事#xff0c;不要在意细节。
pythonnet是 python 和.net无缝连接的桥梁。那么python的图像是numpy表示#xff0c;C#图象是Bitmap。
做图像想要python的便利又想要dotnet的强大就需要图像类型转换。
上程序。
1.Bi…C#是dotnet的代表虽然不是一个东西但是在这里代表同一件事不要在意细节。
pythonnet是 python 和.net无缝连接的桥梁。那么python的图像是numpy表示C#图象是Bitmap。
做图像想要python的便利又想要dotnet的强大就需要图像类型转换。
上程序。
1.Bitmap_转opencv-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(), dtypenp.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
import clr
import numpy as np
import cv2
from System.IO import MemoryStreamclr.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, dtypenp.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()