分享

【cv2模块 python3】

 O听_海_轩O 2020-04-05

Python opencv模块cv2安装和部分函数使用

前几天做了一下验证码识别,在这里分享一下用到的opencv模块cv2部分函数的使用方法,也是给自己加深一下记忆。

一、cv2模块安装

在这里提醒一下这里有
你如果直接用pip install cv2会报错欧
在这里插入图片描述
往下看解决办法
可以通过pip install opencv-python来进行安装

如果pip不能安装还可以通过 https://pypi.tuna./simple/opencv-python寻找自己python对应的 .whl文件下载进行安装,我这安装的是opencv_python-3.1.0.5-cp36-cp36m-win_amd64.whl 其中cp36是我的python版本是3.6版的,自我感觉3.6版本的.whl文件还比较好找,只是自我观点amd64是我安装的python是64位的

二、cv2模块的使用和函数介绍

1、cv2模块的使用

检测cv2是否安装成功

import cv2

在这里插入图片描述
如果不报错就是已经安装成功

2、cv2模块的函数介绍

下面来介绍一下cv2模块的函数介绍

(1)cv2.imread() 读入图片

参数1:图片所在位置
提示:如果想显示网页上的图片还可以写参数1还可以写成网页的网址欧

import cv2

# 读入图像
img = cv2.imread("./2.jpg")

# 显示图像
cv2.imshow("bug", img)
cv2.waitKey(10)  # 单位毫秒
cv2.destroyWindow("bug")

# 复制图像
new_img = img.copy()

# 保存图像
cv2.imwrite("bug-new.png", new_img)
(2)cv2.VideoCapture() 读取图片

参数1:可以为0和1,也可以去获取网络摄像头的网址
cv2.VideoCapture(0)表示获取电脑的摄像头
cv2.VideoCapture(1) 表示获取电脑外部连接的摄像头
cv2.VideoCapture(http://192.168.0.1:8080/?action=snapshot) 表示获取网络摄像头的视频

import cv2

cap = cv2.VideoCapture(0)   #调整参数实现读取视频或调用摄像头
while (cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow("cap", frame)
    if (cv2.waitKey(100) & 0xff) == ord('q'):   #在一个给定的时间内(单位ms)等待用户按键触发
        break
cap.release()
cv2.destroyAllWindows()
(3)cv2.cvtColor() 颜色转换

参数1:所以转换的图片

参数2:要转换的模式 cv2.COLOR_BGR2GRAY:转换为灰度图。cv2.COLOR_BGR2HSV:转换为HSV颜色空间。

(4)cv2.threshold() 二值化

参数1:要灰度的图片

参数2:阈值

参数3:最大值

参数4:转换方式 cv2.THRESH_BINARY、cv2.THRESH_BINARY_INV、cv2.THRESH_TRUNC、cv2.THRESH_TOZERO、cv2.THRESH_TOZERO_INV

(5)cv2.medianBlur() 滤波

参数1:要滤波的图片

参数2:滤波尺寸大小

(6)cv2.boundingRect() 求包含轮廓的正方框

参数1:要计算的某一轮廓

(7)cv2.findContours() 提取图片轮廓

参数1:要提取轮廓的图片

参数2:提取规则。cv2.RETR_EXTERNAL:只找外轮廓,cv2.RETR_TREE:内外轮廓都找。

参数3:输出轮廓内容格式。cv2.CHAIN_APPROX_SIMPLE:输出少量轮廓点。cv2.CHAIN_APPROX_NONE:输出大量轮廓点。

输出参数1:提取轮廓后的图片

输出参数2:轮廓列表

输出参数3:层级

下面附上我的一个验证码识别的代码

# -*- coding: utf-8 -*-

import os
import cv2
import numpy as np

def split_picture(imagepath):

    # 以灰度模式读取图片
    gray = cv2.imread(imagepath, 0)

    # 将图片的边缘变为白色
    height, width = gray.shape
    for i in range(width):
        gray[0, i] = 255
        gray[height-1, i] = 255
    for j in range(height):
        gray[j, 0] = 255
        gray[j, width-1] = 255

    # 中值滤波
    blur = cv2.medianBlur(gray, 3) #模板大小3*3

    # 二值化
    ret,thresh1 = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)

    # 提取单个字符
    chars_list = []
    image, contours, hierarchy = cv2.findContours(thresh1, 2, 2)
    for cnt in contours:
        # 最小的外接矩形
        x, y, w, h = cv2.boundingRect(cnt)
        if x != 0 and y != 0 and w*h >= 100:
            chars_list.append((x,y,w,h))

    sorted_chars_list = sorted(chars_list, key=lambda x:x[0])
    for i,item in enumerate(sorted_chars_list):
        x, y, w, h = item
        cv2.imwrite('test_verifycode/%d.jpg'%(i+1), thresh1[y:y+h, x:x+w])

def remove_edge_picture(imagepath):

    image = cv2.imread(imagepath, 0)
    height, width = image.shape
    corner_list = [image[0,0] < 127,
                   image[height-1, 0] < 127,
                   image[0, width-1]<127,
                   image[ height-1, width-1] < 127
                   ]
    if sum(corner_list) >= 3:
        os.remove(imagepath)

def resplit_with_parts(imagepath, parts):
    image = cv2.imread(imagepath, 0)
    os.remove(imagepath)
    height, width = image.shape

    file_name = imagepath.split('/')[-1].split(r'.')[0]
    # 将图片重新分裂成parts部分
    step = width//parts     # 步长
    start = 0             # 起始位置
    for i in range(parts):
        cv2.imwrite('./test_verifycode/%s.jpg'%(file_name+'-'+str(i)),                     image[:, start:start+step])
        start += step

def resplit(imagepath):

    image = cv2.imread(imagepath, 0)
    height, width = image.shape

    if width >= 64:
        resplit_with_parts(imagepath, 4)
    elif width >= 48:
        resplit_with_parts(imagepath, 3)
    elif width >= 26:
        resplit_with_parts(imagepath, 2)

# rename and convert to 16*20 size
def convert(dir, file):

    imagepath = dir+'/'+file
    # 读取图片
    image = cv2.imread(imagepath, 0)
    # 二值化
    ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
    img = cv2.resize(thresh, (16, 20), interpolation=cv2.INTER_AREA)
    # 保存图片
    cv2.imwrite('%s/%s' % (dir, file), img)

# 读取图片的数据,并转化为0-1值
def Read_Data(dir, file):

    imagepath = dir+'/'+file
    # 读取图片
    image = cv2.imread(imagepath, 0)
    # 二值化
    ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
    # 显示图片
    bin_values = [1 if pixel==255 else 0 for pixel in thresh.ravel()]

    return bin_values

def predict(VerifyCodePath):

    dir = './test_verifycode'
    files = os.listdir(dir)

    # 清空原有的文件
    if files:
        for file in files:
            os.remove(dir + '/' + file)

    split_picture(VerifyCodePath)

    files = os.listdir(dir)
    if not files:
        print('查看的文件夹为空!')
    else:

        # 去除噪声图片
        for file in files:
            remove_edge_picture(dir + '/' + file)

        # 对黏连图片进行重分割
        for file in os.listdir(dir):
            resplit(dir + '/' + file)

        # 将图片统一调整至16*20大小
        for file in os.listdir(dir):
            convert(dir, file)

        # 图片中的字符代表的向量
        files = sorted(os.listdir(dir), key=lambda x: x[0])
        table = np.array([Read_Data(dir, file) for file in files]).reshape(-1,20,16,1)

        # 模型保存地址
        mp = './verifycode_Keras.h5'
        # 载入模型
        from keras.models import load_model
        cnn = load_model(mp)
        # 模型预测
        y_pred = cnn.predict(table)
        predictions = np.argmax(y_pred, axis=1)

        # 标签字典
        keys = range(31)
        vals = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'N',
                'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z']
        label_dict = dict(zip(keys, vals))

        return ''.join([label_dict[pred] for pred in predictions])

def main():

    dir = './VerifyCode/'
    correct = 0
    for i, file in enumerate(os.listdir(dir)):
        true_label = file.split('.')[0]
        VerifyCodePath = dir+file
        pred = predict(VerifyCodePath)

        if true_label == pred:
            correct += 1
        print(i+1, (true_label, pred), true_label == pred, correct)

    total = len(os.listdir(dir))
    print('\n总共图片:%d张\n识别正确:%d张\n识别准确率:%.2f%%.'          %(total, correct, correct*100/total))

main()

如需要下载以上代码和验证码可点击下面链接进行下载链接: https://pan.baidu.com/s/18yvxdn3_sD1tIjUrf56o9Q 
如果发现错误可联系我欧

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多