OpenCV Using Python——加载和显示图像

OpenCV加载和显示图像

1. Python代码

       代码的功能很基础,所以注释也很基础。具体的内容可以查看OpenCV 3的官方文档。

       运行代码需要安装Python和导入OpenCV。在Python命令行输入“import cv2”,如果没有错误说明导入成功。代码如下:

################################################################################

print 'Display Image Using Matplotlib'

import cv2
import numpy as np

imgFile = 'images/face.jpg'

# load an original image
img = cv2.imread(imgFile,1)

# image type is None if image path is wrong
print type(img)

# display an original image
cv2.imshow('Original Image',img)

# load a color image
imgRgb = cv2.imread(imgFile, cv2.IMREAD_COLOR)
# load an image including alpha channel
imgAlpha = cv2.imread(imgFile, cv2.IMREAD_UNCHANGED)
# load a gray image
imgGray = cv2.imread(imgFile, cv2.IMREAD_GRAYSCALE)

# print image shape: (rows, cols, channels)
print 'RGB shape: ', imgRgb.shape
print 'ARGB shape:', imgAlpha.shape
print 'Gray shape:', imgGray.shape

# print image type
print 'img.dtype: ', img.dtype
# print image size
print 'img.size: ', img.size

# display resized square image
cv2.namedWindow('Resized Image', cv2.WINDOW_NORMAL)
cv2.imshow('Resized Image', imgGray)

k = cv2.waitKey(0)
if 27 == k:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif ord('s') == k: # wait for 's' key to save and exit
    # write an image
    cv2.imwrite('face_gray.jpg',imgGray)
    cv2.destroyAllWindows()
    
print 'Goodbye!'
################################################################################

print 'Display Image Using Matplotlib'

# warning: opencv loads images in BGR mode, but matplotlib displays them in RGB mode
from matplotlib import pyplot as plt

# load a gray image
img = cv2.imread(imgFile,0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
# hide tick values on X and Y axis
plt.xticks([]), plt.yticks([])
plt.show()

2. 运行结果

       实验分两个部分,中间需要按键操作才能继续。结果如下:


结语

整个Python OpenCV跑下来真正能直接用的代码不多,大多数Demo在现实中都会引入很多不确定性的噪声。先打好基础吧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值