zoukankan      html  css  js  c++  java
  • Python_opencv库

    1.车牌检测

    '''
    项目名称:opencv/cv2 车牌检测


    简介:
    1.训练级联表 ***.xml 【跳过...】
    2.用如下代码加载级联表和目标图片识别车牌

    注:推荐用anconda安装opencv库
    '''


    import cv2
    detector = cv2.CascadeClassifier() #实例化检测器 detector/检测器
    ret = detector.load('plate_cascade.xml') #加载级联表,注:Python加载文件需要load(加载)一下,C++不需要
    # 检测级联表是否加载成功
    if not ret:
    print('未找到级联表/load cascade err')
    quit()
    # 读目标图片
    img = cv2.imread('2.jpg')
    #转灰度(黑白色)
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY ) #三字节颜色转一字节颜色(彩色转黑白) cvt/转换 covert
    '''
    颜色检测
    颜色转换
    色彩BGR、HVS两种格式
    '''

    # 目标锁定盒子
    boxs = detector.detectMultiScale(gray,1.01,3) #两个参数:金字塔层级系数(1~2之间,与车牌在整张图中的占比成反比;越小越检查出来的多),非相关性抑制系数
    print(len(boxs)) #找到的目标的个数
    for box in boxs:
    x,y,w,h=box # zy 位置 wh宽高
    g=img[y:y+h,x:x+w,:]
    name='%d_%d_%d_%d.jpg'%(x,y,w,h)
    print(name) # 输出车牌截图名称【注:坐标命名规则】
    cv2.imwrite(name,g) # 打印车牌的截图

    2.图片人脸检测

    # 人脸识别,正则分析
    
    import cv2
    import numpy as np
    from PIL import Image
    #pip install PIL
    #pip install opencv-python
    #pip install dlib
    dector=cv2.CascadeClassifier()
    ret=dector.load('haarcascade_frontalface_alt_tree.xml')
    if not ret:
        print('未找到级联表文件:plate_cascade.xml')
        exit()
    
    img=cv2.imread('e:/85n.jpg')
    if img is None:
        print('文件不存在')
        exit()
    #彩色转成灰度图像
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # 正则化,亮度调成均匀的
    gray=np.uint8(gray/gray.ptp()*255)
    
    boxs=dector.detectMultiScale(gray,1.015,1)
    platelist=[]
    for box in boxs:
        x,y,w,h=box
        g=img[y:y+h,x:x+w,:]
        platelist.append(g)
        linew=h//100+1
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),linew)
    gimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    image=Image.fromarray(gimg)
    image.show()
    image.close()

    3.视频人脸检测

    # 人脸识别,正则分析
    
    import cv2
    import numpy as np
    from PIL import Image
    #pip install PIL
    #pip install opencv-python
    #pip install dlib
    dector=cv2.CascadeClassifier()
    ret=dector.load('haarcascade_frontalface_alt_tree.xml')
    if not ret:
        print('未找到级联表文件:plate_cascade.xml')
        exit()
    
    img=cv2.imread('e:/85n.jpg')
    if img is None:
        print('文件不存在')
        exit()
    #彩色转成灰度图像
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # 正则化,亮度调成均匀的
    gray=np.uint8(gray/gray.ptp()*255)
    
    boxs=dector.detectMultiScale(gray,1.015,1)
    platelist=[]
    for box in boxs:
        x,y,w,h=box
        g=img[y:y+h,x:x+w,:]
        platelist.append(g)
        linew=h//100+1
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),linew)
    gimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    image=Image.fromarray(gimg)
    image.show()
    image.close()

    4.数字识别

    # -*- coding: utf-8 -*-
    """
    Created on Thu May 17 19:30:13 2018
    
    @author: AI04班级
    """
    
    import cv2
    import numpy as np
    from PIL import Image  #Python Image Lib
    import skimage.feature as feature2d
    import sklearn.neighbors as nhb
    from sklearn.externals import joblib  #对训练模型保存或读取
    #cvhog=cv2.HOGDescriptor()
    
    
    def imgPrepare(filename):
        img=cv2.imread(filename,0)
        img=np.uint8(img/img.ptp()*255)
        img=np.where(img>128,255,img)
        img=np.where(img<=128,0,img)
        img=np.bitwise_not(img)
        return img
        
    def splitchar(img,axis=1):
        idxrowb=np.all(img<64,axis=axis)
        idxrowi=np.uint8(idxrowb).ravel()
        dy=idxrowi[1:]-idxrowi[:-1]
        #print(dy)
        rowb=np.argwhere(dy==255).ravel()
        rowe=np.argwhere(dy==1).ravel()
        #print(rowb,rowe)
        if axis==1:
            imglines=[img[b:e+1,:] for b,e in zip(rowb,rowe)]
        else:
            imglines=[img[:,b:e+1] for b,e in zip(rowb,rowe)]
      
        return imglines
    
    def splitBox(img):
        idxrowb=np.all(img<64,axis=1)
        idxrowi=np.uint8(idxrowb).ravel()
        dy=idxrowi[1:]-idxrowi[:-1]
        #print(dy)
        rowb=np.argwhere(dy==255).ravel()
        rowe=np.argwhere(dy==1).ravel()
        b=0
        e=-1
        if len(rowe)>0:
            e=rowe[-1]+1
        if len(rowb)>0:
            b=rowb[0]
            
            
        return img[b:e,:]
    
    def myResize(img,size=(48,48)):
        h,w=img.shape
        bw=max(h,w)
        bh=bw
        bimg=np.zeros((bh,bw),np.uint8)
        if bw==w:
            dh=(bh-h)//2
            bimg[dh:dh+h,:]=img[:,:]
        else:
            dw=(bw-w)//2
            bimg[:,dw:dw+w]=img[:,:]
            
        bimg=cv2.resize(bimg,size)
        return bimg
    
    def getHog(img,cell=(16,16),block=(3,3)):
        vec=feature2d.hog(img,12,cell,block,'L2')
        return vec
    #main
    gimg=imgPrepare('e:/sx.jpg')
    lines=splitchar(gimg,axis=1)
    chars=[]
    for line in lines:
        charlist=splitchar(line,axis=0)
        cchars=[  myResize(splitBox(c))  for c in charlist]
        chars.append(cchars)
    chars=np.asarray(chars)
    X=[]
    Y=[]
    y=0
    for linech in chars:
        
        for ch in linech:
            chhog=getHog(ch)
            X.append(chhog)
            Y.append(y)
        
        y+=1
    
    KNC=nhb.KNeighborsClassifier(algorithm='ball_tree',n_neighbors=3)
    KNC.fit(X,Y)
    
    joblib.dump(KNC,'knc.knn')
    
    def predict(img):
         knc=nhb.KNeighborsClassifier(algorithm='ball_tree',n_neighbors=3)
         knc=joblib.load('knc.knn')
         lines=splitchar(img,axis=1)
         chars=[]
         for line in lines:
             charlist=splitchar(line,axis=0)
             cchars=[  myResize(splitBox(c))  for c in charlist]
             chars.append(cchars)
        
         chars=np.asarray(chars)
        
         Y=[]
         for linech in chars:
            x=[]
            for ch in linech:
                chhog=getHog(ch)
                x.append(chhog)
                
            y=knc.predict(x)
            print(y)
            Y.append(y)
        
         return Y
  • 相关阅读:
    如何发现需求
    测试linux和window下 jdk最大能使用多大内存
    java获取汉字的拼音 简单版
    oracle一条sql执行导入sql文件
    oracle使用闪回功能恢复删除的表数据
    linux环境变量配置
    有两张表;使用SQL查询,查询所有的客户订单日期最新的前五条订单记录。 糖不苦
    jQuery作业 点击出弹框 糖不苦
    #{}和${}的区别是什么? 糖不苦
    在html页面中如何使用jQuery? 糖不苦
  • 原文地址:https://www.cnblogs.com/hellangels333/p/9042967.html
Copyright © 2011-2022 走看看