1. 图片读取方式
读取图片,并设置图片大小
-
keras 导入
img = load_img(image_path, target_size=target_input) # 设置导入尺寸 plt.imshow(img)
-
opencv 导入
img = cv2.imread(image_path) img = cv2.resize(img, target_input[:2]) # cv.resize 值只接受(h, w)
2. 绘图
2.1 图片显示
-
opencv 绘制 (默认 gbr)
cv2.imshow(windown, img) # window 可以随意命名
若不能正常显示:
cv2.waitKey(0) # 键盘绑定函数,等待按键 cv2.destroyAllWindows() # 按下键盘中的按键,启动该程序销毁所有窗口
-
plt 显示
使用
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
可以先将opencv读取的bgr转化为plt可以读取的bgr格式plt.imshow() plt.show()
2.2 关闭坐标显示
plt.xticks([]) # 关闭x坐标显示
plt.yticks([]) # 关闭y坐标显示
3. 保存图片
保存在当前目录下(或者使用绝对地址)
plt.savefig('./result.jpg')
4. 实例
- 矩阵边线
# Python program to explain cv2.rectangle() method
# importing cv2
import cv2
# path
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'
# Reading an image in default mode
image = cv2.imread(path)
# Window name in which image is displayed
window_name = 'Image'
# Start coordinate, here (5, 5)
# represents the top left corner of rectangle
start_point = (5, 5)
# Ending coordinate, here (220, 220)
# represents the bottom right corner of rectangle
end_point = (220, 220)
# Blue color in BGR
color = (255, 0, 0)
# Line thickness of 2 px
thickness = 2
# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)
# Displaying the image
cv2.imshow(window_name, image)
- 实心矩阵
# Python program to explain cv2.rectangle() method
# importing cv2
import cv2
# path
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'
# Reading an image in grayscale mode
image = cv2.imread(path, 0)
# Window name in which image is displayed
window_name = 'Image'
# Start coordinate, here (100, 50)
# represents the top left corner of rectangle
start_point = (100, 50)
# Ending coordinate, here (125, 80)
# represents the bottom right corner of rectangle
end_point = (125, 80)
# Black color in BGR
color = (0, 0, 0)
# Line thickness of -1 px
# Thickness of -1 will fill the entire shape
thickness = -1
# Using cv2.rectangle() method
# Draw a rectangle of black color of thickness -1 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)
# Displaying the image
cv2.imshow(window_name, image)