!!!欢迎来到我的博客站点~

Opencv 图像处理

cmd.exe  安装命令行

》pip install opencv-python

》pip install tensorflow  

》pip install keras      必须安装tensorflow基础之上

 

板块一、

     几何图形(cv2 图像处理)

 

图片导入;
图片长宽通道数学;
图片裁剪;
图片输出;
图片保存文件;

tu = cv2.imread('image.jpg')
(h,w,t)=tu.shape
print(tu.shape)
cX,cY = (w//2,h//2)
print(cX)
tl = tu[0:cY,0:cX]
tr = tu[0:cY,cX:w]
bl = tu[cY:h,0:cX]
br = tu[cY:h,cX:w]
def zzImage(zhou):
    plt.imshow(zhou)
    plt.axis('off')
    plt.show()
zzImage(br)
#   裁剪顺序  先y,再x

cv2.imwrite('newImage.jpg',image)

 封装常用函数 代码块(.py文件)

包含图片旋转代码

 
import cv2
import matplotlib.pyplot as plt
import numpy as np

#读取图片
def imgRead(src):
   src = cv2.imread(src)
   return cv2.cvtColor(src,cv2.COLOR_BGR2RGB)
#显示图片
def imgShow(img):
    plt.imshow(img)
    plt.axis('off')
    plt.show()
def imgWrite(Img):
    return cv2.imwrite('newImage.jpg',Img)



img = imgRead('face.png')
imgShow(img)
#imgWrite(img)

#看图片的信息 
(h,w,t)=img.shape  
print(img.shape)
#得出图片的中心点
cX,cY=(w//2,h//2)
#写一个 动作 ,旋转动作   (旋转中心点,旋转角度,缩放的倍数)
Action = cv2.getRotationMatrix2D((cX,cY),90,1.0)
#外容器执行旋转动作  存储图片
img = cv2.warpAffine(img,Action,(w,h))
imgShow(img)
View Code

 使用引入格式: from 文件名 import *

设置图片大小+等比例算法: imgW = 80
imgH = int(img.shape[0]*imgW/img.shape[1])
img= cv2.resize(img,(imgW,imgH))
show(img)
print(img.shape)

人脸检测方法初学:

#定义人脸检测方法
def check(image):
    detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')  #写入这个 简单的xml文件
    rects = detector.detectMultiScale(image,scaleFactor=1.1,minNeighbors=3,minSize=(10,10),flags=cv2.CASCADE_SCALE_IMAGE)
    for (x,y,w,h) in rects:
          cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)
img = imread('Solvay.jpg')       
check(img)
show(img)

 

板块二、

     一、画图

导包 import numpy as np
import cv2
import matplotlib.pyplot as plt
显示函数 def show(image):
    plt.imshow(image)
    plt.axis('off')
    plt.show()
创建一个 300 300 画布 image = np.zeros((300,300,3),dtype='uint8')
画线 green = (0,255,0)
cv2.line(image, (0,0), (300,300), green)
正方形 -1 为填充 cv2.rectangle(wrap,(3,3),(296,296),(120,120,120),5)
(cX,cY) = wrap.shape[1]//2,wrap.shape[0]//2
for i in range(0,140,15):
    cv2.circle(wrap,(cX,cY),i,green,2)
cv2.circle(wrap,(cX,cY),15,(255,0,0),-1)
show(wrap)

 content = np.zeros((300,300,3),dtype='uint8')
for z in range(15):
   #随机的半径
    Rban = np.random.randint(0,150)
    #随机的圆心
    Rxin = tuple(np.random.randint(0,300,size=(2)))
    #随机的颜色
    Rcolor = np.random.randint(0,255,size=(3)).tolist()
    cv2.circle(content,Rxin,Rban,Rcolor,-1)
show(content)

 

 二、翻转

导包不说了 cv2  matplotlib.pyplot

水平翻转  1

垂直翻转  0

水平+垂直 -1

cv2.finp(image,1)

 三、裁剪

  裁剪就是:把图片的某一块坐标数值,存起来显示   

       avater = image[0:0,200,200]   打印输出

 四、图像算术

   

加像素 add = np.ones(wrap.shape,dtype='uint8')*100
coo = cv2.add(wrap,add)
show(coo)
减像素 shan = np.ones(wrap.shape,dtype='uint8')*205
cww = cv2.subtract(wrap,shan)
show(cww)
 

 五、按位计算

与 1&1=1,1&0=0,0&1=0,0&0=0 and = cv2.bitwise_and(box1,box2)
或1|1=1,1|0=1,0|1=1,0|0=0 or = cv2.bitwise_or(box1,box2)  
异或1^1=0,1^0=1,0^1=1,0^0=0 xor = cv2.bitwise_xor(box1,box2)  
1=0,0=1  not= cv2.bitwise_not(wrap)  

 五、遮挡

#导入一张图片

img = cv2.imread('cat.jpg')

#创建一个 跟图片相同大小的容器

wrap = np.zeros(img.shap,dtype='uint8')

#创建一个盒子

squen = cv2.rectangle(wrap,(25,25),(250,350),白色,-1)

#进行按位计算  得出新的图片

newImg = cv2.bitwise_and(wrap,img)

show(newImg)

   

 五、单通道切割

mm = cv2.imread('cat.jpg')
show(mm)

(R,G,B) = cv2.split(mm)
mm.shape

meraged = cv2.merge([R,G,B])
show(meraged)

cv2.imshow('R',R)
cv2.imshow('G',G)
cv2.imshow('B',B)
cv2.waitKey(0)
cv2.destroyAllWindows()
 

 六、图像金字塔

nn = cv2.imread('image.jpg')
show(nn)
nn.shape

 



for u in range(4):
    nn = cv2.pyrDown(nn)
    print(nn.shape)
    show(nn)

for u in range(4):
    nn = cv2.pyrUp(nn)
    print(nn.shape)
    show(nn)

 七、拉普拉斯金字塔(提取图像边界轮廓的)

yuan = cv2.imread('image.jpg')
show(yuan)
yuan.shape

#第一次降低
down_image1 = cv2.pyrDown(yuan)
#第二次降低
down_image2 = cv2.pyrDown(down_image1)
#第三次提升
up_image = cv2.pyrUp(down_image2)
#第一次降低  减去 最后一次  得出的就是 结果
lapulasi = down_image1 - up_image
show(lapulasi)

 

 

板块三、  形态学(卷积)

      一、Erode腐蚀     .erode()

#设置腐蚀 Erision   黑色多一点  白色小时
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
tuoyuan = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
shizi = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))

imagea = cv2.erode(imga,juxing)
show(imagea)

去除白色,黑色多

     二、Dilate膨胀      .dilate()

#膨胀 dilate 黑色多一点  白色小时
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
tuoyuan = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
shizi = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))

imagea = cv2.dilate(imga,juxing)
show(imagea)

去除白色,黑色多

      三、Opening开运算

#先腐蚀后膨胀
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

opening= cv2.morphologyEx(imga,cv2.MORPH_OPEN,juxing)
show(opening)

专业去除白色小点

     四、Closing闭运算 相反

#先膨胀后腐蚀
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

closing= cv2.morphologyEx(imga,cv2.MORPH_CLOSE,juxing)
show(closing)

专业去除嘿色小点

     五、先开后闭运算

#先膨胀后腐蚀
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
imgb = cv2.imread('image2.jpg')
opening= cv2.morphologyEx(imgb,cv2.MORPH_OPEN,juxing)
colseing= cv2.morphologyEx(opening,cv2.MORPH_CLOSE,juxing)
show(colseing)

 

     六、梯度运算


juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

closing= cv2.morphologyEx(imga,cv2.MORPH_GRADIENT,juxing)
show(closing)

膨胀 - 腐蚀  =出现图像的轮廓线

     七、白帽运算作用:隐藏的白色显示

#
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

closing= cv2.morphologyEx(imga,cv2.MORPH_TopHat,juxing)
show(closing)

src - opening

     八、黑帽运算作用:隐藏的黑色显示

#
juxing = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

closing= cv2.morphologyEx(imga,cv2.MORPH_CLOSE,juxing)
show(closing)

colseing-src

      颜色模式转换 (RGB/HSV/LAB/GRAY)

               hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)    转为 HSV

板块四、  二值化(阈值)     就是讲一张图片 转为黑白两个颜色  形成对比

           五种简单模式:   

gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
plt.imshow(gray,'gray')
plt.axis('off')
plt.show()

ret1,thresh1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
ret2,thresh2 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
ret3,thresh3 = cv2.threshold(gray,127,255,cv2.THRESH_TRUNC)
ret4,thresh4 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO)
ret5,thresh5 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO_INV)

titles = ['original','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [gray, thresh1, thresh2, thresh3, thresh4, thresh5]
plt.figure(figsize=(15,5))
for i in range(6):
    plt.subplot(2,3,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.axis('off')
plt.show()
View Code

 

        作用:自动化阈值(全局阈值),相当于这个抠图   

#自动化阈值  代码如下:

img = cv2.imread('opencv_logo.png')
#转换为灰度
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
#定义 自动阈值
ret1,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
print('ret1',ret1)

#普通灰度
plt.imshow(gray,'gray')
plt.axis('off')
plt.show()

#打印自动阈值
plt.imshow(thresh1,'gray')
plt.axis('off')
plt.show()

#打印自动阈值
plt.imshow(thresh2,'gray')
plt.axis('off')
plt.show()

   Adaptive Thresholding自适应阈值

       我们使用是全局阈值,整幅图像采用同一个数作为阈值。这个是 每一个区域对应一个阈值,自适应  一张图有不同的阈值。

# 变灰度图
image = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
# 中值滤波
image = cv2.medianBlur(image,5)
# 普通二值化
ret,th1 = cv2.threshold(image,127,255,cv2.THRESH_BINARY)
# 平均值阈值
th2 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,3)
# 高斯阈值
th3 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,3)
titles = ['original', 'Global Thresholding', 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [image, th1, th2, th3]
plt.figure(figsize=(10,5))
for i in range(4):
    plt.subplot(2,2,i+1)
    plt.imshow(images[i],'gray')
    plt.axis('off')
    plt.title(titles[i])
plt.show()

 

 

       

   图像梯度:OpenCV 提供了三种不同的梯度滤波器,或者说高通滤波器: Sobel,Scharr 和 Laplacian    (算子)

          出现X轴、Y轴  单向的颜色模糊模式,或者是 XY都有的  第二图  那张。

def gradient(image):
    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    # cv2.CV_64F输出图像的深度(数据类型),64位float类型,因为梯度可能是正也可能是负
    laplacian = cv2.Laplacian(image, cv2.CV_64F)
    # 1, 0表示在x方向求一阶导数,最大可以求2阶导数
    sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
    # 0, 1表示在y方向求一阶导数,最大可以求2阶导数
    sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
    titles = ['Original', 'Laplacian', 'SobelX', 'SobelY']
    images = [image,laplacian,sobelx,sobely]
    plt.figure(figsize=(10,5))
    for i in range(4):
        plt.subplot(2,2,i+1)
        plt.imshow(images[i],'gray')
        plt.title(titles[i])
        plt.axis('off')
    plt.show()

gradient(image)

 

 

 

    Canny边缘检测:

def edge_detection(image,minVal=100,maxVal=200):
    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    edges = cv2.Canny(image,minVal,maxVal)
    plt.imshow(edges,'gray')
    plt.axis('off')
    plt.show()

 

 

# 自动确定阈值的一种方法
def auto_canny(image, sigma=0.33):
    v = np.median(image)
    lower = int(max(0, (1.0-sigma) * v))
    upper = int(min(255, (1.0+sigma) * v))
    edged = cv2.Canny(image, lower, upper)
    print(lower,upper)
    return edged

 

edges = auto_canny(image)
edges = cv2.GaussianBlur(edges, (3,3), 0)
plt.imshow(edges,'gray')
plt.axis('off')
plt.show()

    摄像头画面获取:

import numpy as np
import cv2

#从摄像获取 图像画面  
cap  = cv2.VideoCapture(0)

while(True):
    #ret 读取成功True 或  失败 False
    #Frame 读取的图像 的内容
    #读取一帧数据
    ret,frame = cap.read()
    #变为灰度图片
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)

# 监控键盘输入,如果键值是 q 那么久跳出 while循环
    if cv2.waitKey(1) & 0xff == ord('w'):
            break
cap.release()
cv2.destroyAllWindows()

 

 

    视频文件读取:

# 从文件读取视频内容
cap = cv2.VideoCapture('videos/cats.mp4')
# 视频每秒传输帧数
fps = cap.get(cv2.CAP_PROP_FPS)
# 视频图像的宽度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# 视频图像的长度
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(fps)
print(frame_width)
print(frame_height)

#循环读取图像帧
while(True):
    ret,frame = cap.read()
    if ret !=True:
        break
    cv2.imshow('frame',frame)

#waitKey()  设置图像延迟播放  速率
    if cv2.waitKey(25) & 0xff ==  ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

 

    写入视频文件读取:

           读取视频文件,读取写入的文件,将文件A 修改翻转,写入到文件B

import numpy as np
import cv2

# 从文件读取视频内容
cap = cv2.VideoCapture('videos/cats.mp4')
# 视频每秒传输帧数
fps = cap.get(cv2.CAP_PROP_FPS)
# 视频图像的宽度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# 视频图像的长度
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(fps)
print(frame_width)
print(frame_height)

 

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('video/output.avi',fourcc,fps,(frame_width,frame_height))

while(True):
    ret, frame = cap.read()
    if ret==True:
        # 水平翻转
        frame = cv2.flip(frame,0)
        out.write(frame)
        cv2.imshow('frame',frame)
        if cv2.waitKey(25) & 0xff == ord('q'):
            break
    else:
        break
out.release()
cap.release()
cv2.destroyAllWindows()

 

     10.人脸检测Haar特征+Adaboost级联分类器:

            Haar 就是通过移动滑块收集特征,最小24*24,最大就是白黑白跟滑块边缘的宽度一致,使用卷积再滑块盒子中移动检测。

            摄像头人脸检测:

#从摄像获取 图像画面  
cap  = cv2.VideoCapture(0)

detector = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')

while(True):
    #ret 读取成功True 或  失败 False
    #Frame 读取的图像 的内容
    ret,image = cap.read()
    #image = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    
    # 级联分类器
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=2, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE)
    for (x,y,w,h) in rects:
        # 画矩形框
        cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)
        
    cv2.imshow('人脸识别',image)
    if cv2.waitKey(1) & 0xff == ord('w'):
            break
cap.release()
cv2.destroyAllWindows()

 

 


 

posted @ 2019-08-27 11:18  Haisen'Blogs  阅读(3711)  评论(0编辑  收藏  举报

reeber

开车啦

1
2
3
4
5
/* 看板娘 */