Python cv2.imdecode() 函數用於從內存緩存中讀取圖像數據並將其轉換為圖像格式。這通常用於從 Internet 有效地加載圖像。
用法:cv2.imdecode(buf,flags)
參數:
- buf - 它是以字節為單位接收到的圖像數據
- flags - 它指定讀取圖像的方式。默認值為 cv2.IMREAD_COLOR
返回:圖像陣列
注意:如果給定的 buf 不是圖像數據,則將返回 NULL。
範例1:
Python3
#import modules
import numpy as np
import urllib.request
import cv2
# read the image url
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
with urllib.request.urlopen(url) as resp:
# read image as an numpy array
image = np.asarray(bytearray(resp.read()), dtype="uint8")
# use imdecode function
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# display image
cv2.imwrite("result.jpg", image)
輸出:
範例2:如果需要灰度,則可以使用 0 作為標誌。
Python3
# import necessary modules
import numpy as np
import urllib.request
import cv2
# read image url
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
with urllib.request.urlopen(url) as resp:
# convert to numpy array
image = np.asarray(bytearray(resp.read()), dtype="uint8")
# 0 is used for grayscale image
image = cv2.imdecode(image, 0)
# display image
cv2.imwrite("result.jpg", image)
輸出:
範例3:從文件中讀取圖像
輸入圖片:
Python3
# import necessayr modules
import numpy as np
import urllib.request
import cv2
# read th image
with open("image.jpg", "rb") as image:
f = image.read()
# convert to numpy array
image = np.asarray(bytearray(f))
# RGB to Grayscale
image = cv2.imdecode(image, 0)
# display image
cv2.imshow("output", image)
輸出:
相關用法
- Python OpenCV setWindowTitle()用法及代碼示例
- Python OpenCV resizeWindow()用法及代碼示例
- Python OpenCV waitKey()用法及代碼示例
- Python OpenCV waitKeyEx()用法及代碼示例
- Python OpenCV getRotationMatrix2D()用法及代碼示例
- Python OpenCV destroyAllWindows()用法及代碼示例
- Python OpenCV namedWindow()用法及代碼示例
- Python OpenCV selectroi()用法及代碼示例
- Python OpenCV getTrackbarPos()用法及代碼示例
- Python OpenCV Filter2D()用法及代碼示例
- Python OpenCV Canny()用法及代碼示例
- Python OpenCV setTrackbarPos()用法及代碼示例
- Python OpenCV getgaussiankernel()用法及代碼示例
- Python OpenCV haveImageReader()用法及代碼示例
注:本文由純淨天空篩選整理自bhavyajain4641大神的英文原創作品 Python OpenCV – imdecode() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。