Python [plt 和 cv] 图片读取、显示和保存

1. 图片读取方式

读取图片,并设置图片大小

  1. keras 导入

    img = load_img(image_path, target_size=target_input) # 设置导入尺寸
    
    plt.imshow(img)
    
  2. opencv 导入

    img = cv2.imread(image_path)
    img = cv2.resize(img, target_input[:2])   # cv.resize 值只接受(h, w)
    

2. 绘图

2.1 图片显示

  1. opencv 绘制 (默认 gbr)

    cv2.imshow(windown, img)  # window 可以随意命名
    

    若不能正常显示:

    cv2.waitKey(0)  # 键盘绑定函数,等待按键
    cv2.destroyAllWindows() # 按下键盘中的按键,启动该程序销毁所有窗口
    
  2. 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) 

参考

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值