Python中的opencv图片处理

安装

  • conda install opencv-python

如果发生错误:PackagesNotFoundError: The following packages are not available from current channels: - opencv-python

- anaconda show conda-forge/opencv-python
- conda install --channel https://conda.anaconda.org/conda-forge opencv 
1
2
import numpy as np
import cv2

读取图片 imread

1
2
cat = cv2.imread('./cat.jpg')
cat
array([[[167, 181, 187],
        [167, 181, 187],
        [167, 181, 187],
        ...,
        [209, 225, 231],
        [212, 228, 234],
        [215, 231, 237]],

       [[168, 182, 188],
        [168, 182, 188],
        [169, 183, 189],
        ...,
        [215, 231, 237],
        [215, 231, 237],
        [218, 234, 240]],

       [[170, 184, 190],
        [171, 185, 191],
        [171, 185, 191],
        ...,
        [214, 228, 234],
        [213, 227, 233],
        [214, 228, 234]],

       ...,

       [[184, 195, 199],
        [184, 195, 199],
        [186, 197, 201],
        ...,
        [202, 212, 219],
        [201, 211, 218],
        [201, 211, 218]],

       [[184, 195, 199],
        [186, 197, 201],
        [185, 196, 200],
        ...,
        [198, 208, 215],
        [203, 213, 220],
        [207, 217, 224]],

       [[186, 197, 201],
        [189, 200, 204],
        [186, 197, 201],
        ...,
        [195, 205, 212],
        [203, 213, 220],
        [210, 220, 227]]], dtype=uint8)
1
cat.shape
(600, 404, 3)

显示图片 imshow

1
2
3
4
5
cv2.imshow('cat',cat)
#窗口等待任意键盘按键输入,0为一直等待,其他数字为毫秒数
cv2.waitKey(0)
# 销毁窗口
cv2.destroyAllWindows()

颜色空间转换 cvtColor

1
2
3
4
5
# BGR 蓝绿红 cv2读取图片,颜色通道是BGR
# PIL 读取图片,颜色通道 RGB
# 将图片转为灰度
cat1 = cv2.cvtColor(cat,code=cv2.COLOR_BGR2GRAY)
cat1
array([[181, 181, 181, ..., 225, 228, 231],
       [182, 182, 183, ..., 231, 231, 234],
       [184, 185, 185, ..., 228, 227, 228],
       ...,
       [195, 195, 197, ..., 213, 212, 212],
       [195, 197, 196, ..., 209, 214, 218],
       [197, 200, 197, ..., 206, 214, 221]], dtype=uint8)
1
2
3
cv2.imshow('gray',cat1)
cv2.waitKey(0)
cv2.destroyAllWindows()
1
cv2.COLOR_BGR2GRAY
6

保存图片

1
cv2.imwrite('./cat1.jpg',cat1)
True
1
cat1.shape
(600, 404)
1
2
3
4
cat2 = cv2.resize(cat,dsize=(300,500))
# 缩放图片
# cat2 = cv2.resize(cat,(200,200))
cat2.shape
(500, 300, 3)
1
2
3
cv2.imshow('cat2',cat2)
cv2.waitKey(0)
cv2.destroyAllWindows()

图片翻转

cv2.filp(img,flipcode)

  • flipcode = 0:沿x轴翻转
  • flipcode > 0:沿y轴翻转
  • flipcode < 0:x,y轴同时翻转
1
2
3
4
catflip = cv2.flip(cat,-1)
cv2.imshow('catflip',catflip)
cv2.waitKey(0)
cv2.destroyAllWindows()

图片复制 copy

1
2
cat5 = cat.copy()
cat5.shape
(600, 404, 3)

Python中的opencv图片处理

http://fahsa.cn/python/test-opencv1/

作者

Fahsa

发布于

2021-01-11

更新于

2021-01-11

许可协议

评论