湖南網(wǎng)站設(shè)計(jì)公司西安優(yōu)化seo
C#是dotnet的代表雖然不是一個(gè)東西但是在這里代表同一件事,不要在意細(xì)節(jié)。
pythonnet是 python 和.net無(wú)縫連接的橋梁。那么python的圖像是numpy表示,C#圖象是Bitmap。
做圖像想要python的便利又想要dotnet的強(qiáng)大就需要圖像類型轉(zhuǎn)換。
上程序。
1.Bitmap_轉(zhuǎn)opencv-python
import clr
import numpy as np
import cv2
from System.IO import MemoryStream
clr.AddReference('System.Drawing')
from System.Drawing import Bitmap# 確保已經(jīng)加載了System.Drawing程序集# 假設(shè)你已經(jīng)有了一個(gè)Bitmap對(duì)象
# 例如,從文件加載一個(gè)Bitmap對(duì)象
bitmap = Bitmap("8.bmp")# 將Bitmap轉(zhuǎn)換為字節(jié)數(shù)組
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函數(shù)將字節(jié)數(shù)組解碼為Mat對(duì)象
mat = cv2.imdecode(bitmap_data, cv2.IMREAD_COLOR)# 現(xiàn)在你可以使用OpenCV的功能處理這個(gè)Mat對(duì)象了
# 例如,將其轉(zhuǎn)換為灰度圖像
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轉(zhuǎn)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格式轉(zhuǎn)換為RGB格式
cv_image_rgb = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)# 創(chuàng)建一個(gè)與圖像數(shù)據(jù)相匹配的numpy數(shù)組
h, w, c = cv_image_rgb.shape
numpy_array = np.array(cv_image_rgb, dtype=np.uint8).reshape((h, w, c))# 創(chuàng)建一個(gè)MemoryStream對(duì)象并將numpy數(shù)組寫(xiě)入
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創(chuàng)建Bitmap對(duì)象
bitmap = Bitmap.FromStream(stream)# 現(xiàn)在你有一個(gè)System.Drawing.Bitmap對(duì)象,可以在.NET環(huán)境中使用
# 例如,保存到文件
bitmap.Save("output_image.png", Imaging.ImageFormat.Png)# 清理資源
stream.Close()