OpenCV入门——基本图像操作

处理灰度图片

读入图像
OpenCV可以读入不同类型的图像 (PNG, JPG, etc)。可以上传灰度图片、彩色图片或者带Alpha通道的图片。使用cv2.imread()函数,语法规则见下:

retval = cv2.imread( filename [, flags])

retval:成功载入的图片,否则为None。当路径不对或者图片损坏时会发生。
该函数有一个必须的输入参数和一个可选择参数。
1、filename:可以是绝对路径,也可以是相对路径。这是必须传入的参数
2、Flags:这个参数用来表示用哪种特定格式读入一张图片(如,灰度/彩色/带有alpha通道)。这是一个可选参数,默认值为cv2.IMREAD_COLOR1,代表作为彩色图片载入。
Flags
1、cv2.IMREAD_GRAYSCALE0:以灰度模式载入图片。
2、cv2.IMREAD_COLOR1:以彩图模式载入图片,图片的透明度会被忽略,这是默认值。
3、cv2.IMREAD_UNCHANGED-1:包含alpha通道载入图片
OpenCV Documentation
Imread:https://docs.opencv.org/4.5.1/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56
ImreadModes:https://docs.opencv.org/4.5.1/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80

import cv2
import numpy as np 
import matplotlib.pyplot as plt
# Read image as gray scale
cb_img = cv2.imread('checkerboard_18x18.png', 0)
# Print the image data (pixel values), element of a 2D numpy array
# Each pixel value is 8-bit2 [0, 255]
print(cb_img)

在这里插入图片描述
打印图片属性

# Print the size of image
print('Image size is ', cb_img.shape)
# Print data-type of image
print('Data type of image is ', cb_img.dtype)

'''
Image size is  (18, 18)
Data type of image is  uint8
'''

用matplotlib展示图片

# Display image.
plt.imshow(cb_img)

在这里插入图片描述
尽管图片以灰度图片的方式被读入,当使用imshow()的时候不一定按照灰度图的方式展示。matplotlib使用不同的color map,可能没有设置灰度color map。

# Set color map to gray scale for proper rendering.
plt.imshow(cb_img, cmap='gray')

在这里插入图片描述
另一实例

# Read images as gray scale.
cb_img_fuzzy = cv2.imread("checkerboard_fuzzy_18x18.jpg", 0)

# Print image.
print(cb_img_fuzzy)

# Display image.
plt.imshow(cb_img_fuzzy, cmap='gray')

在这里插入图片描述
在这里插入图片描述

处理彩色图片

读入和展示图片

# Read in image.
coke_img = cv2.imread("coca-cola-logo.png", 1)

# Print the size of image
print
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值