1. 程式人生 > >影象處理的基本操作(load, display, save)

影象處理的基本操作(load, display, save)

影象處理的基本操作(load, display, save)

文章目錄

load

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

cv2.imread(filename[, flags])

display

影象的顯示需要藉助matplotlib.pyplot.imshow()函式。

# Display an image, i.e. data on a 2D regular raster.
import matplotlib.pyplot as plt
plt.imshow(image)

save

The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format.

cv2.imwrite(filename, img[, params])

示例

import cv2
import matplotlib.pyplt as plt

image = cv2.imread("image.jpg") # 載入圖片
print("Height: %d pixels" % (image.shape[0])) # 影象高度
print("Width: %d pixels" % (image.shape[1])) # 影象寬度
print("Channels: %d" % (image.shape[2])) # 影象通道數

# Open CV讀取圖片是BGR模式
# matplotlib顯示圖片時是按照RGB模式,因此在顯示之前需要做轉換 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #將BGR模式資料轉為RGB模式資料 plt.imshow(image) #顯示影象 plt.axis("off") #刪除座標軸 plt.show() # 圖片儲存 cv2.imwrite("new_image.jpg", image)