这些相当于我的学习笔记,所以并没有很强的结构性和很全的介绍,请见谅。

1. 读取/写入图像

下面是一个简短的载入图像、打印尺寸、转换格式及保存图像为.png的例子:

# -*- coding: utf-8 -*-
import cv2
import numpy as np
# 读入图像
im = cv2.imread('../data/empire.jpg') # 打印图像尺寸
h, w = im.shape[:2]
print h, w # 保存原jpg格式的图像为png格式图像
cv2.imwrite('../images/ch10/ch10_P210_Reading-and-Writing-Images.png',im)

# 注:imread默认读取的是RGB格式,所以即使原图像是灰度图,读出来仍然是三个通道,所以,在imread之后可以添加参数

# 注:这里是相对路径: \与/是没有区别的,‘’ 和 “” 是没有区别的。 ../表示返回到上一级目录下,./表示与该源码文件同一级目录下。

"\"这种斜杠使用需要用转义字符,即"\\"表示单“\”。而“/” 不需要转义字符,即单个斜杠就可以了。所以在使用时,形式如下:
im = cv2.imread('../data/empire.jpg')
im = cv2.imread('..\\data\\empire.jpg')

# 注:函数imread()将图像返回为一个标准的NumPy数组。

1.1 相关注释

cv2.imread

Python: cv2.imread(filename[, flags])

Parameters:
  • filename – Name of file to be loaded.
  • flags –

    Flags specifying the color type of a loaded image:

    • CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
    • CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
    • CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one
    • >0 Return a 3-channel color image.

      Note

      In the current implementation the alpha channel, if any, is stripped from the output image. Use negative value if you need the alpha channel.

    • =0 Return a grayscale image.   如果是灰度图就用这个就好了。例如:cv2.imread'../data/empire.jpg',0)
    • <0 Return the loaded image as is (with alpha channel).

cv2.imwrite

Python: cv2.imwrite(filename, img[, params])

Parameters:
  • filename – Name of the file.
  • image – Image to be saved.
  • params –

    Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, ... . The following parameters are currently supported:

    • For JPEG, it can be a quality ( CV_IMWRITE_JPEG_QUALITY ) from 0 to 100 (the higher is the better). Default value is 95.
    • For PNG, it can be the compression level ( CV_IMWRITE_PNG_COMPRESSION ) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
    • For PPM, PGM, or PBM, it can be a binary format flag ( CV_IMWRITE_PXM_BINARY ), 0 or 1. Default value is 1.

2.图像RGB/HSV 通道分离

# Convert BGR to r,g,b
b,g,r = cv2.split(im) # Convert BGR to HSV
image_hue_saturation_value = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
h,s,v=cv2.split(image_hue_saturation_value) # Convert BGR to gray
image_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

# 注:RGB channels is indexed in B G R which is different from matlab。

# 注:Any channels could be split using cv2.split, pay attention to the sequence of channels

2.1 相关注释

Python: cv2.split(m[, mv]) → mv

Parameters:
  • src – input multi-channel array.
  • mv – output array or vector of arrays; in the first variant of the function the number of arrays must match src.channels(); the arrays themselves are reallocated, if needed.

Python: cv2.cvtColor(src, code[, dst[, dstCn]]) → dst

Parameters:
  • src – input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point.
  • dst – output image of the same size and depth as src.
  • code – color space conversion code (see the description below).
  • dstCn – number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code .

3.图像矩阵的操作(点乘,复制,截取,1到N维矩阵)

# mask seed 3D matrix
seed_mask_single_channel_list = np.array([[[1,0,0],[0,0,0],[0,0,0]],[[0,1,0],[0,0,0],[0,0,0]],[[0,0,1],[0,0,0],[0,0,0]],
                   [[0,0,0],[1,0,0],[0,0,0]],[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,0,1],[0,0,0]],
                   [[0,0,0],[0,0,0],[1,0,0]],[[0,0,0],[0,0,0],[0,1,0]],[[0,0,0],[0,0,0],[0,0,1]]])
# cut image
image_new_sample = image_source[:200,:200] #取前200个行和列的元素,python是从0开始的,所以0:200表示的是0-199这200个元素,取不到200.而初始位置0可以省略 #separate channel
mask_singel_channel = np.tile(seed_mask_single_channel_list[1],(70,70))[:200,:200] #第一个3*3的mask作为一个单元进行复制成为70行,70列,截取前200行,200列
single_channel_image = mask_singel_channel * image_new_sample #表示点乘

# 注:矩阵的操作用Numpy这个类库进行。

3.1 相关注释

numpy.array(objectdtype=Nonecopy=Trueorder=Nonesubok=Falsendmin=0)

Parameters:

object : array_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

dtype : data-type, optional

The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.

copy : bool, optional

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtypeorder, etc.).

order : {‘C’, ‘F’, ‘A’}, optional

Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is ‘A’, then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).

subok : bool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

ndmin : int, optional

Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

Returns:

out : ndarray

An array object satisfying the specified requirements.

e.g.  最外层始终都是[],所以如果是1维就一个[],2维就2个,N维就N个

>>> np.array([1, 2, 3])
array([1, 2, 3])
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

numpy.tile(A, reps)

Parameters:

A : array_like

The input array.

reps : array_like

The number of repetitions of A along each axis.

Returns:

c : ndarray

The tiled output array

e.g.

>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])

Python + OpenCV2 系列:2 - 图片操作的更多相关文章

  1. Python + OpenCV2 系列:1 - 配置

    Python+OpenCV2+Eclipse+Windos 8.1(32bits): 最初的目的是做图像处理,opencv强大的社区支持,让我想从matlab转到opencv框架下进行试验,而Pyth ...

  2. Python语言系列-03-文件操作和函数

    ## 深浅拷贝 #!/usr/bin/env python3 # author:Alnk(李成果) # 赋值运算 # 可变的数据类型:由于数据类型可变,修改数据会在原来的数据的基础上进行修改, # 可 ...

  3. Python + OpenCV2 系列:3 - python 字符串,类,编码规范

    首先,强烈推荐<<简明 Python 教程>> Swaroop, C. H. 著 沈洁元 译 其实,这本书里已经把python的最基本的用法,编码等等介绍的很好,这里把我用到的 ...

  4. [js高手之路] html5 canvas系列教程 - 图片操作(drawImage,clip,createPattern)

    接着上文[js高手之路] html5 canvas系列教程 - 文本样式(strokeText,fillText,measureText,textAlign,textBaseline)继续,本文介绍的 ...

  5. Python学习系列之文件操作

    Pyhton文件打开方式 with= open('文件路径','打开模式') as f:#PS:python3提供了with语句来帮我们自动调用close方法,所以说无论打开文件是否出错都能自动正确的 ...

  6. media静态文件统一管理 操作内存的流 - StringIO | BytesIO PIL:python图片操作库 前端解析二进制流图片(了解) Admin自动化数据管理界面

    一.media ''' 1. 将用户上传的所有静态文件统一管理 -- settings.py -- MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 2. 服务 ...

  7. Python学习系列(五)(文件操作及其字典)

    Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件      在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...

  8. Python系列之文件操作、冒泡算法、装饰器、及递归

    文件处理 python对文件进行读写操作的方法与具体步骤,包括打开文件.读取内容.写入文件.文件中的内容定位.及关闭文件释放资源等 open().file(),这个两函数提供了初始化输入\输出(I\O ...

  9. 用 Python 和 OpenCV 检测图片上的条形码

      用 Python 和 OpenCV 检测图片上的的条形码 这篇博文的目的是应用计算机视觉和图像处理技术,展示一个条形码检测的基本实现.我所实现的算法本质上基于StackOverflow 上的这个问 ...

随机推荐

  1. poj1236 强连通缩点

    Network of Schools Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 15211   Accepted: 60 ...

  2. js-新窗口打开页面

    window.open(basePath+"/web/homeIndex?code="+code); 1.超链接<a href="http://www.xxx.ne ...

  3. 输入一个数组,求最小的K个数

    被这道题困了好久,看了剑指Offer才知道OJ上的要求有点迷惑性. 题目: 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4. 一 ...

  4. 虚拟机NAT模式无法上网问题的解决办法

    在使用CentOS虚拟机时,出现了无法上网的情况,使用主机ping虚机地址可以ping通,而虚机ping不通主机,同时虚机也无法ping通其他的网址或ip,显示内容为Network is unreac ...

  5. oracle 11g 新特性UTL_TCP、UTL_HTTP 和 UTL_SMTP程序包发邮件

    首先,创建一个 ACL: begindbms_network_acl_admin.create_acl (acl             => 'utlpkg.xml', ---创建的访问控制列 ...

  6. win10 1607 密匙

    win10 1607 安装密钥 GVLK Core=YTMG3-N6DKC-DKB77-7M9GH-8HVX7 Professional=VK7JG-NPHTM-C97JM-9MPGT-3V66T E ...

  7. ecshop /flow.php SQL Injection Vul

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 ECSHOP的配送地址页面网页没有验证地区参数的有效性,存在sql注入漏 ...

  8. Linux Default Bootup、Startup、Autoload Configuration file(自启动服务脚本)

    目录 . Linux初始化init系统 . Linux配置文件自动加载过程 1. Linux初始化init系统 Linux初始化init系统在不同操作系统系列下的区别 . RHEL : SysVini ...

  9. Unity 依赖注入知识点

    三种依赖注入方法,构造器注入.属性注入.方法注入 可以配置Config文件,来实现不用修改代码.需要先将接口与实体关联,然后使用时会自动加载对应实体. namespace WeChatConsole ...

  10. hdu 2005 - 第几天?

    题意:判断是否为闰年 解法:这题需要注意一下用scanf能直接读入year,month,day 附上代码: 1: #include<stdlib.h> 2: #include<str ...