Opencv入门

1、图片的读取与展示

import  cv2
img = cv2.imread('test.jpg',0) # 1:图片名称 2: 1彩色图片 0 灰度图片
cv2.imshow('image',img) # 1:展示窗口名称
cv2.waitKey(0)

2、图片的写入

#图片的写入
import cv2
img = cv2.imread('test.jpg',1)
# 1:要保存的文件名 2;保存文件的原始数据
#3: 保存JPG图片 有损压缩 0--100 :数字越大,质量越高
# cv2.imwrite('copytest.jpg',img,[cv2.IMWRITE_JPEG_QUALITY,5])
#保存png图片 无损 透明操作 0--9 :数字越大,质量越低
cv2.imwrite('copytest.jpg',img,[cv2.IMWRITE_PNG_COMPRESSION,0])
像素.png

像素的写入

import cv2
img = cv2.imread('test.jpg',1)
(b,g,r) = img[100, 100]#返回的是bgr的值
print(b,g,r)
for i in range(100):
    img[10+i,100]=(255,0,0)
cv2.imshow('image',img)
cv2.waitKey(0)

tf的变量定义

import tensorflow as tf
#常量
data1 = tf.constant(10,dtype=tf.int32)
sess = tf.Session()
print(sess.run(data1))
#变量
data2 = tf.Variable(20,name='val')
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(data2))

tf 的四则运算

import tensorflow as tf
data1 = tf.constant(2)
data2 = tf.Variable(6)
dataAdd = tf.add(data1,data2)
datacopy = tf.assign(data2,dataAdd) # dataAdd-->data2
dataMui = tf.multiply(data1,data2)
dataSub = tf.subtract(data1,data2)
dataDvi = tf.divide(data1,data2)
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    print(sess.run(dataAdd))
    print(sess.run(dataMui))
    print(sess.run(dataSub))
    print(sess.run(dataDvi))
    print(sess.run(datacopy)) # 8
    print(datacopy.eval())    #10
    print(tf.get_default_session().run(datacopy)) #12

placeholder的使用

import tensorflow as tf
data1 = tf.placeholder(tf.float32)
data2 = tf.placeholder(tf.float32)
dataAdd = tf.add(data1,data2)
with tf.Session() as sess:
    print(sess.run(dataAdd,feed_dict={data1:2,data2:6}))

矩阵的定义和读取操作

import tensorflow as tf
data = tf.constant([[1,2],
                    [3,4],
                    [5,6]])
with tf.Session() as sess:
    print(data.shape)
    print(sess.run(data))
    print(sess.run(data[0]))#打印第一行
    print(sess.run(data[:,0]))#答应第一列

矩阵的加法和除法

import tensorflow as tf
data1 = tf.constant([[1,2]])
data2 = tf.constant([[3],
                     [4]])
datamul = tf.matmul(data1,data2)#矩阵乘法
datamulti = tf.multiply(data1,data2)#数乘
dataadd = tf.add(data1,data1)

with tf.Session() as sess:
    print(sess.run(datamul))
    print(sess.run(dataadd))
    print(sess.run(datamulti))
    print(sess.run([datamul,dataadd,datamulti]))

特殊矩阵

import tensorflow as tf
mat0 = tf.constant([[1, 2,3]])
mat1 = tf.zeros([3,2])        #3行2列的全0 矩阵
mat2 = tf.ones([3,3])         #3行3列的全1 矩阵
mat3 = tf.fill([2,1],15)      #2行1列的全15 矩阵
mat4 = tf.linspace(1.0,2.0,11)#将1 到2 10等分
mat5 = tf.random_uniform([3,2],1,100)#3行2列的矩阵 1--100的水机数
mat6 = tf.zeros_like(mat0)           #和mat0一样的形状的全0矩阵
with tf.Session() as sess:
    print(sess.run(mat6))

malplotlib的使用

import numpy as np
import  matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6])
y = np.array([4,5,7,4,9,1])
plt.plot(x,y,color='blue',lw=10)

x = np.array([1,2,3,4,5,6])
y = np.array([4,5,7,4,9,1])
plt.bar(x,y,0.5,color='red',alpha=1,)#0.5表示条形图填充的面积百分比
plt.show()

股票逼近案例

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
day = np.linspace(1,7,7)
open = np.array([2673.07,2723.89,2691.43,2777.25,2780.74,2769.02,2791.40])
close = np.array([2698.47,2668.97,2705.19,2723.26,2780.96,2785.87,2795.31])

for i in range(0,7):
    onday = np.zeros([2])
    onday[0] = i+1
    onday[1] = i+1

    price = np.zeros([2])
    price[0] = open[i]
    price[1] = close[i]
    if open[i]

图片的缩放

import cv2
img = cv2.imread('test.jpg',1)
shape = img.shape
print(shape)
height = shape[0]
width = shape[1]
dstheight = int(height*0.5)
dstwidth = int(width*0.5)
dst = cv2.resize(img,(dstwidth,dstheight))
cv2.imshow('resize',dst)
cv2.waitKey(0)

图片缩放的源代码实现

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
dstheight = int(height/2)
dstwidth = int(width/2)
dst = np.zeros((dstheight,dstwidth,3),np.uint8)#0-255
for  i in range(0,dstheight):
    for j in range(0,dstwidth):
        iNew = int(i*(width/dstwidth))
        jNew = int(j*(height/dstheight))
        dst[i,j] = img[iNew,jNew]
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的剪切

import cv2
img = cv2.imread('test.jpg',1)
print(img.shape)
dst = img[100:300,200:400]
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的移位

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
cv2.imshow('original',img)
shape = img.shape
height = shape[0]
width = shape[1]
matShift = np.float32([[1,0,100],[0,1,200]])
dst = cv2.warpAffine(img,matShift,(height,width))
cv2.imshow('dst',dst)
cv2.waitKey(0)

移位的源码实现


import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
dst = np.zeros(img.shape,np.uint8)
height = shape[0]
width = shape[1]
for i in range(height):
    for j in range(width-100):
        dst[i,j+100] = img[i,j]

cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的翻转

import cv2
import numpy as np
img = cv2.imread('test.png',1)
shape = img.shape
height = shape[0]
width = shape[1]
deep = shape[2]
newImg = (height*2,width,deep)
dst = np.zeros(newImg,np.uint8)

for i in range(0,height):
    for j in range(0,width):
        dst[i,j] = img[i][j]
        dst[2*height-i-1,j] = img[i,j]

for i in range(0,width):
    dst[height,i] = (0,0,255)

cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的放缩

import numpy as np
import cv2
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
maxScale = np.float32([[0.5,0,0],[0,0.5,0]])
dst = cv2.warpAffine(img,maxScale,(int(width/2),int(height/2)))
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的边缘检测

import cv2
import numpy as np
img = cv2.imread('test.jpg',0)
# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgG = cv2.GaussianBlur(img,(3,3),0)
dst = cv2.Canny(img,50,50)
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的旋转

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
#旋转矩阵
# 1 旋转中心 2、旋转角度 3、图片缩放
matRoate = cv2.getRotationMatrix2D((width*0.5,height*0.5),45,0.5)
dst = cv2.warpAffine(img,matRoate,(width,height))
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的灰度处理

'''方法1
import cv2
img = cv2.imread('test.jpg',1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('dst',dst)
cv2.waitKey(0)
'''
#方法2 心理学计算公式 gray = r*0.299 + g*0.587 +b*0.114
import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
    for j in range(0,width):
        (b,g,r) = img[i,j]
        b = int (b)
        g = int (g)
        r = int (r)
        #通过移位熟读更快
        #gray = (b+(g<<1)+r)>>2
        gray = r*0.299 + g*0.587 +b*0.114
        dst[i,j]=gray

cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的马赛克效果

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
for i in range(100,1000):
    for j in range(100,700):
        if i%10==0 and j%10==0:
            (b, g, r) = img[i, j]
            #填充10*10的小方块
            for m in range(1,10):
                for n in range(1,10):

                    img[i+m,n+j]=(b,g,r)
cv2.imshow('dst',img)
cv2.waitKey(0)

毛玻璃效果

import cv2
import numpy as np
import random
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,3),np.uint8)
mm = 8 #上下8像素随机距离
for i in range(height-mm):
    for j in range(width-mm):
        index = int(random.random()*8)#随机生成0-8
        (b,g,r)=img[i+index,j+index]
        dst[i,j]=(b,g,r)

cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的融合

import cv2
import numpy as np
img1 = cv2.imread('test.jpg',1)
img2 = cv2.imread('chenw.jpg',1)
t1 = img1[0:500,0:700]
t2 = img2[0:500,0:700]
dst = np.zeros((500,700,3),np.uint8)
# dst = t1*0.5+t2*0.5
dst = cv2.addWeighted(t1,0.5,t2,0.5,0)
cv2.imshow('dst',dst)
cv2.waitKey(0)

边缘检测

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
#灰度处理
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#高斯滤波
imgG = cv2.GaussianBlur(img,(3,3),0)
#Canny处理 大于50认为为结果点
dst = cv2.Canny(imgG,50,50)
cv2.imshow('dst',dst)
cv2.waitKey(0)

图片卷积源码实现

import cv2
import numpy as np
import math
img = cv2.imread('test.jpg',0)
img = cv2.resize(img,(400,300))
shape = img.shape
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,1),np.uint8)
for i in range(0,height-2):
    for j in range(0,width-2):
        '''
        [1,2,1
        0.,0,
        -1,-2,-1
        ]
        [
        1,0,-1
        2,0,-2
        1,0,-1
        ]
        '''
        gy = img[i,j]*1+img[i,j+1]*2+img[i,j+2]*1-(img[i+2,j]*1+img[i+2,j+1]*2+img[i+2,j+2]*1)
        gx = img[i,j]*1+img[i+1,j]+2+img[i+2,j]*1-(img[i,j+2]*1+img[i+1,j+2]+2+img[i+2,j+2]*1)
        gr = math.sqrt(gx*gx+gy*gy)
        if gr>50:
            dst[i,j] = 255
        else :
            dst[i,j] = 0

cv2.imshow('dst',dst)
cv2.waitKey(0)

图片的浮雕效果

import cv2
import numpy as np
import math
img = cv2.imread('test.jpg',0)
shape = img.shape
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,1),np.uint8)
for i in range(0,height):
    for j in range(0,width-1):
        gray0 = int(img[i,j])
        gray1 = int(img[i,j+1])
        newGrey = gray0-gray1+150
        if newGrey>255:
            newGrey=255
        elif newGrey<0:
            newGrey=0
        dst[i,j]=newGrey
cv2.imshow('dst',dst)
cv2.waitKey(0)

线段的绘制

import cv2
import numpy as np
imginfo = (500,500,3)
img = np.zeros(imginfo,np.uint8)
#              begin     end      cololr     line_width line_typr  
cv2.line(img,(200,200),(400,400),(0,255,255),20,cv2.LINE_AA)
cv2.imshow('img',img)
cv2.waitKey(0)

基本图形的绘制

import cv2
import numpy as np
imgInfo = (500,400,3)
dst = np.zeros(imgInfo,np.uint8)
#                 2:左上角  3:右下角   4:颜色    5:-1表示填充 大于0表示线条宽度
cv2.rectangle(dst,(100,100),(200,200),(255,0,0),-1)
#
cv2.circle(dst,(50,50),(50),(0,255,0),-1)
#椭圆                                0-360度
cv2.ellipse(dst,(300,300),(100,50),0,0,360,(0,0,255),-1)
cv2.imshow('dst',dst)
cv2.waitKey(0)

文字的写入

'''
import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
font = cv2.FONT_HERSHEY_PLAIN
cv2.putText(img,'this a girl',(20,200),font,2,(0,255,20),3,cv2.LINE_AA)
cv2.imshow('img',img)
cv2.waitKey(0)
'''
import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
height = int(img.shape[0]*0.2)
width = int(img.shape[1]*0.2)
tem = cv2.resize(img,(width,height))
for i in range(0,height):
    for j in range(0,width):
        img[i+200,j+200] = tem[i,j]

cv2.imshow('img',img)
cv2.waitKey(0)

彩色图片直方图

import cv2
import numpy as np

def getHist(img,type):
    color = (255,255,255)
    if type == 33:
        color = (255,0,0)
    elif type ==34:
        color = (0,255,0)
    elif type == 35:
        color = (0,0,255)
    #注意全部中括号        2:灰度 3:mask 4:范围 5:颜色范围
    hist = cv2.calcHist([img],[0],None,[255],[0.0,255.0])
    maV,maxV,minL,maxL = cv2.minMaxLoc(hist)
    histIng = np.zeros([255,255,3],np.uint8)
    for n in range(0,255):
        interNormal = int(hist[n]*256/maxV)
        cv2.line(histIng,(n,256),(n,256-interNormal),color)
    cv2.imshow('name',histIng)
    cv2.waitKey(0)

img = cv2.imread('test.jpg',1)
channels = cv2.split(img)
for i in range(0,3):
    getHist(channels[i],33+i)

直方图均衡化

# import cv2
# img = cv2.imread('test.jpg',0)
# cv2.imshow('img',img)
# #dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# dst = cv2.equalizeHist(img)
# cv2.imshow('dst',dst)
# cv2.waitKey(0)
# import cv2
# img = cv2.imread('test.jpg',1)
# (b,g,r) = cv2.split(img)
# bH = cv2.equalizeHist(b)
# gH = cv2.equalizeHist(g)
# rH = cv2.equalizeHist(r)
# res = cv2.merge((bH,gH,rH))
# cv2.imshow('res',res)
# cv2.waitKey(0)

import cv2
img = cv2.imread('test.jpg',1)
tem = cv2.cvtColor(img,cv2.COLOR_BGR2YCrCb)
channelYUV = cv2.split(tem)
channelYUV[0] = cv2.equalizeHist(channelYUV[0])
channel = cv2.merge(channelYUV)
res = cv2.cvtColor(channel,cv2.COLOR_YCR_CB2BGR)
cv2.imshow('res',res)
cv2.waitKey(0)

图片的修补

import cv2
import numpy as np

img = cv2.imread('bandgirl.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
paint = np.zeros((height,width,1),np.uint8)
for i in range(200,300):
    paint[i,250] = 255
    paint[i,250+1] = 255
    paint[i,250-1] = 255

for i in range(200,300):
    paint[250,i] = 255
    paint[250+1,i] = 255
    paint[250-1,i] = 255
#                 坏图片 蒙版数组
dst = cv2.inpaint(img,paint,3,cv2.INPAINT_TELEA)
cv2.imshow('dst',dst)
cv2.waitKey(0)

双边滤波

import cv2
img = cv2.imread('test.jpg',1)
dst = cv2.bilateralFilter(img,15,50,50)
cv2.imshow('img',img)
cv2.imshow('dst',dst)
cv2.waitKey(0)

中值滤波:对6*6的范围求均值

import cv2
import numpy as np
img = cv2.imread('test.jpg',1)
shape = img.shape
height = shape[0]
width = shape[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(3,height-3):
    for j in range(3,width-3):
        sum_b = int(0)
        sum_g = int(0)
        sum_r = int(0)
        for m in range(-3,3):
            for n in range(-3,3):
                (b,g,r) = img[i+m,j+n]
                sum_b = sum_b+int(b)
                sum_g = sum_g+int(g)
                sum_r = sum_r+int(r)
        b = np.uint8(sum_b/36)
        g = np.uint8(sum_g/36)
        r = np.uint8(sum_r/36)
        dst[i,j] = (b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey(0)

视频截取图片

import cv2
cap = cv2.VideoCapture('test.mp4')
isOpen = cap.isOpened
fps = cap.get(cv2.CAP_PROP_FPS)#帧数
heigth  = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print(fps,heigth,width)
i = 0
while(isOpen):
    imgName = 'img'+str(i)+'.jpg'
    (flag,frame) =cap.read()#读取图片
    if flag==True:
        cv2.imwrite(imgName,frame)

    i=i+1
    if i==10:
        break

图片合成视频

import cv2
img = cv2.imread('img0.jpg')
size = (img.shape[1],img.shape[0])
print(size)
videoWriter = cv2.VideoWriter('chini.avi',-1,15,size)
for i in range(1,10):
    fname = 'img'+str(i)+'.jpg'
    img=cv2.imread(fname)
    videoWriter.write(img)
print('end!')

人脸识别

import cv2
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

face_xml = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_xml = cv2.CascadeClassifier('haarcascade_eye.xml')

#检测人脸                              缩放量 脸的最小尺寸>5
face = face_xml.detectMultiScale(gray,1.1,5)
print('face',len(face))
for (x,y,w,h) in face:
    cv2.rectangle(img,(x,y),(y+h,x+w),(255,0,0),2)
    eye_gray = gray[y:y+h,x:x+w]
    eye_color = img[y:y+h,x:x+w]
    eyes = eye_xml.detectMultiScale(eye_gray,1.1,5)
    print('eyes',len(eyes))
    for (e_x,e_y,e_w,e_h) in eyes:
        cv2.rectangle(eye_color, (e_x, e_y), (e_y + e_h, e_x + e_w), (0, 255, 0), 2)

cv2.imshow('face',img)
cv2.waitKey(0)
print('end!')

SVM

import cv2
import numpy as np
import matplotlib.pyplot as plt
ran1 = np.array([[150,50],[153,49],[160,55],[165,58],[170,60]])
ran2 = np.array([[152,60],[160,63],[165,68],[170,69],[180,75]])

label = np.array([[0],[0],[0],[0],[0],[1],[1],[1],[1],[1]])
ran = np.vstack((ran1,ran2))
ran = np.array(ran,dtype='float32')
print(ran)

#训练
svm = cv2.ml.SVM_create()
#属性
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)#线性分类
svm.setC(0.01)

result = svm.train(ran,cv2.ml.ROW_SAMPLE,label)
#预测数据
pr_data = np.vstack([[170,69],[150,49]])
pr_data = np.array(pr_data,dtype='float32')
(res1,res2) = svm.predict(pr_data)
print(res2)

hog特征


hog1

image.png

你可能感兴趣的:(Opencv入门)