1. 图像读、显、存
# import the lib of opencv
import cv2
img_file = './monarch.png'
# 1. read an image in RGB format
img = cv2.imread(img_file, 1)
# 2. show the image
cv2.imshow('monarch',img)
# wait until key strokes
cv2.waitKey(0)
# close all cv2 windows after key strokes
cv2.destroyAllWindows()
# 3. save the image in JPG format
cv2.imwrite('monarch.jpg', img)
2. 图像属性:
空间分辨率:spatial resolution
灰度分辨率(用数据类型表示):data type
图像字节数:Size
import cv2
import numpy as np
img_file = './monarch.png'
# 1. read in RGB format
rgb = cv2.imread(img_file, cv2.COLOR_BGR2RGB)
# 2. Check the resolution, data type, and number of bytes
print('RGB: Shape: ', np.shape(rgb), ', Type: ', type(rgb[0][0][0]), 'Size: ', np.size(rgb))
输出结果:
RGB: Shape: (512, 768, 3) , Type: <class 'numpy.uint8'> Size: 1179648
3. 使用matplotlib显示图像
import numpy as np
import cv2
import matplotlib.pyplot as plt
img_file = './stdimage/monarch.bmp'
# 1. read an image using cv2
rgb = cv2.imread(img_file, cv2.COLOR_BGR2RGB)
# 2. adapt to show by matplot
rgb_plt = rgb[:, :, ::-1]
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
gray_plt = gray
_, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
binary_plt = binary
# 3. Show figures using matplot
fig = plt.figure('Matplot')
plt.subplot(221)
plt.imshow(rgb[:, :, ::-1])
plt.title('RGB: cv2')
plt.xticks([])
plt.yticks([])
plt.subplot(222)
plt.imshow(rgb_plt)
plt.title('RGB')
plt.axis('off')
plt.subplot(223)
plt.imshow(gray_plt, cmap=plt.cm.gray)
plt.title('gray')
plt.axis('off')
plt.subplot(224)
plt.imshow(binary_plt, cmap=plt.cm.gray)
plt.title('binary')
plt.axis('off')
plt.show()
# 4. Save images
fig.tight_layout()
fig.savefig('plt.png', dpi=300, bbox_inches='tight')
显示结果
更多内容,请参考
绘图: matplotlib核心剖析 by Vamei 或
Python绘图总结(Matplotlib篇)之图形分类及保存 by wuzlun