opencv入门

学习视频

NO.1

import cv2 as cv
import numpy as np

#读视频
def video_demo():
    capture=cv.VideoCapture(0)
    while(True):
        ret,frame=capture.read()
        frame=cv.flip(frame,1)
        cv.imshow("vedio",frame)
        c = cv.waitKey(50)
        if c == 27:  # c为按键,常用的,27是ESC
            break


#读图片
def get_image_info(image):
    print(type(image)) #n维
    print(image.shape)
    print(image.size)
    print(image.dtype)
    pixel_data=np.array(image)
    print(pixel_data)



print("------------Hello python------------")
src=cv.imread("D:/images/demo.jpg")
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("input image",src)
get_image_info(src) #读图片
video_demo()  #读视屏
cv.imwrite("D:/images/result.png",src)
gray=cv.cvtColor(src,cv.COLOR_BGR2GRAY)
cv.imwrite("D:/images/gray.png",gray)
cv.waitKey(0)

cv.destroyAllWindows()

NO.2

import cv2 as cv
import numpy as np


#每个像素点的属性(三原色)获取
def access_pixels(image):
    print(image.shape)
    #三个色彩空间 blue green red
    height=image.shape[0]
    width=image.shape[1]
    channels=image.shape[2]
    print("width : %s,height : %s,channels : %s"%(width,height,channels))
    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row,col,c]
                image[row,col,c] = 255 -pv
    cv.imshow("pixels_demo",image)


#inverse 和 access_pixels(image) 一样的效果,但是他的速度快很多
def inverse(image):
    dst = cv.bitwise_not(image)
    cv.imshow("inverse demo",dst)


print("------------Hello python------------")
src=cv.imread("D:/images/demo.jpg")
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)

cv.imshow("input image",src)
#t1 = cv.getTickCount()
#access_pixels(src)
inverse(src)
#t2 = cv.getTickCount()
# blue green red


cv.waitKey(0)

cv.destroyAllWindows()

NO.3

import cv2 as cv
import numpy as np


#每个像素点的属性(三原色)获取
def access_pixels(image):
    print(image.shape)
    #三个色彩空间 blue green red
    height=image.shape[0]
    width=image.shape[1]
    channels=image.shape[2]
    print("width : %s,height : %s,channels : %s"%(width,height,channels))
    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row,col,c]
                image[row,col,c] = 255 -pv
    cv.imshow("pixels_demo",image)


def create_image():
    """
    # 三通道的RGB
    img = np.zeros([400,400,3],np.uint8)
    img[: ,: ,0] = np.ones([400,400])*255 #R
    img[:, :, 1] = np.ones([400, 400]) * 255 #G
    img[:, :, 2] = np.ones([400, 400]) * 255 #B
    cv.imshow("new image",img)
    #单通道的
    img=np.zeros([400,400,1],np.uint8)
    img[ : , : ,0]=np.ones([400,400])*127
    cv.imshow("new image",img)
    cv.imwrite("D:/images/create_image.jpg",img)
    n1= np.ones([3,3],np.float32)
    n1.fill(122.234)
    print(n1)
    """




print("------------Hello python------------")
src = cv.imread("D:/images/demo.jpg")
#cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
#cv.imshow("input image",src)
#t1 = cv.getTickCount()
#access_pixels(src)
#t2 = cv.getTickCount()
create_image()
#print((t2-t1)/cv.getTickFrequency()*1000)  # /ms
# blue green red


cv.waitKey(0)

cv.destroyAllWindows()

NO.4

import cv2 as cv
import numpy as np

#对色彩的操作

def color_space_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    cv.imshow("gray",gray)
    # H:[0-180]
    # S:[0-255]
    # v:[0-255]
    hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV)
    cv.imshow("hsv",hsv)
    yuv = cv.cvtColor(image,cv.COLOR_BGR2YUV)
    cv.imshow("yuv",yuv)
    ycrcb = cv.cvtColor(image,cv.COLOR_BGR2YCrCb)
    cv.imshow("ycrcb",ycrcb)


def extrace_object_demo():
    capture = cv.VideoCapture("D:/video/1.点击.mp4")
    while(True):
        ret,frame = capture.read()
        if ret == False :
            break
        hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)
        # 追踪绿色              [H, S, V]
        lower_hsv = np.array([37,43,46]) #查表
        upper_hsv = np.array([77, 255, 255])  # 查表
        mask = cv.inRange(hsv,lower_hsv,upper_hsv) #二值图像
        cv.imshow("video",frame)
        cv.imshow("mask",mask) #追踪有颜色的对象
        c=cv.waitKey(40)
        if c==27:
            break

print("------------Hello python------------")
src=cv.imread("D:/images/demo.jpg")
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("input image",src)

#通道分离
b,g,r = cv.split(src)
#cv.imshow("blue",b)
#cv.imshow("green",g)
#cv.imshow("red",r)

src[:,:,2]=0  #三通道,最后一个通道赋值为0
src = cv.merge([b,g,r])
cv.imshow("changed image",src)
#extrace_object_demo()
cv.waitKey(0)

cv.destroyAllWindows()

NO.5

#分帧指定的视屏
import cv2 as cv
import numpy as np

print("------------Hello python------------")
capture = cv.VideoCapture("D:/video/5.旋转.mp4")
count=0
while (True):
    ret, frame = capture.read()
    if ret == False:
        break
    count=count+1
    cv.imwrite('D:/video/test5/'+ str(count) + ".jpg",frame)
    c = cv.waitKey(40)
    if c == 27:
        break
cv.waitKey(0)

cv.destroyAllWindows()

NO.6

一些运算,加减乘除

import cv2 as cv
import numpy as np
def add_demo(m1,m2):
    dst = cv.add(m1,m2)
    cv.imshow("add_demo",dst)


def subtract_demo(m1,m2):
    dst = cv.subtract(m1,m2)
    cv.imshow("subtract_demo",dst)


def divide_demo(m1,m2):
    dst = cv.divide(m1,m2)
    cv.imshow("divide_demo",dst)


def multiply_demo(m1,m2):
    dst = cv.multiply(m1,m2)
    cv.imshow("multiply_demo",dst)

def others(m1,m2):
    """
    M1 = cv.mean(m1)
    M2 = cv.mean(m2)
    print(M1)
    print(M2)
    """
    M1, dev1=cv.meanStdDev(m1)
    M2, dev2 = cv.meanStdDev(m2)
    h,w = m1.shape[:2]
    print(M1)
    print(M2)
    print(dev1)
    print(dev2) #2方差小
    img = np.zeros([h,w],np.uint8)
    m, dev = cv.meanStdDev(img)
    print(m)
    print(dev)  #判读图像是否有有用的信息

def logic_demo(m1,m2):
    #dst = cv.bitwise_and(m1,m2)
    #dst = cv.bitwise_or(m1, m2)
    dst = cv.bitwise_or(m1, m2)
    cv.imshow("logic_demo",dst)


print("------------Hello python------------")
src1 = cv.imread("D:/images/linux.jpg")
src2 = cv.imread("D:/images/windows.jpg")
#cv.namedWindow("image1",cv.WINDOW_AUTOSIZE)
print(src1.shape)
print(src2.shape)
#cv.imshow("image1",src1)
#cv.imshow("image2",src2)
#add_demo(src1,src2)
#subtract_demo(src1,src2)
#divide_demo(src1,src2)
#multiply_demo(src1,src2)
#others(src1,src2)
#logic运算
logic_demo(src1,src2)
cv.waitKey(0)

cv.destroyAllWindows()

NO.7

import cv2 as cv
import numpy as np

#ROI 泛洪填充
#roi 区域:矩形,
#roi操作 Region of interest
#用numpy获取roi区域

#彩色图像的填充
def fill_color_demo(image):
    copyImg = image.copy()
    h , w = image.shape[:2]
    mask = np.zeros([h+2, w+2],np.uint8) #一定要加2
    cv.floodFill(copyImg,mask,(30,30),(0,255,255),(100,100,100),(50,50,50),cv.FLOODFILL_FIXED_RANGE) #彩色图像flag 写fixed
    cv.imshow("fill_color_demo()",copyImg)

#二值图像的填充
def fill_binary():
    image = np.zeros([400,400,3],np.uint8)
    image[100:300,100:300,:] = 255
    cv.imshow("fill_binary",image)

    mask = np.ones([402,402,1],np.uint8)  #初始化
    mask[101:301,101:301]=0   #初始化 遮罩层为0 才填充
    cv.floodFill(image,mask,(200,200),(100,2,255),cv.FLOODFILL_MASK_ONLY)
    cv.imshow("flood_fill",image)






print("------------Hello python------------")
src = cv.imread("D:/images/lena.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
#cv.imshow("image",src)
#fill_color_demo(src)
fill_binary()
"""
face = src[80:250, 100:220]  ##
gray = cv.cvtColor(face,cv.COLOR_BGR2GRAY)
backface = cv.cvtColor(gray,cv.COLOR_GRAY2RGB)
# cv.imshow("face",gray)
src[80:250,100:220] = backface
cv.imshow("face",src)
"""

cv.waitKey(0)

cv.destroyAllWindows()

NO.8

import cv2 as cv
import numpy as np
"""
模糊操作(卷积原理)
卷积和为奇数
均值模糊
中值模糊
自定义模糊
"""

#均值模糊去噪声
def blur_demo(image):
    dst = cv.blur(image,(5,5))
    cv.imshow("blur_demo",dst)


#处理椒盐噪声
def medianBlur_demo(image):
    dst = cv.medianBlur(image,5)
    cv.imshow("medianBlur_demo",dst)

#锐化unshape mask
def customBlur_demo(image):
    #kernel = np.ones([5,5],np.float32)/25 #自定义卷积核算法
    #kernel = np.array([[1,1,1],[1,1,1],[1,1,1]],np.float32)/9;
    #更有立体感
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32);
    dst = cv.filter2D(image,-1,kernel=kernel)
    cv.imshow("customBlur_demo",dst)


print("------------Hello python------------")
src = cv.imread("D:/images/lena.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
cv.imshow("image",src)
customBlur_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

 

NO.9

import cv2 as cv
import numpy as np
"""
高斯模糊,加高斯噪声
"""

def clamp(pv):
    if pv > 255 :
        return 255
    if pv < 0:
        return 0
    return pv


def gaussian_noise(image):
    h,w,c = image.shape
    for row in range(h):
        for col in range(w):
            s = np.random.normal(0,20,3)
            b = image[row,col,0] #blue
            g = image[row,col,1] #green
            r = image[row,col,2] #red
            image[row, col, 0] = clamp(b + s[0])
            image[row, col, 1] = clamp(g + s[1])
            image[row, col, 2] = clamp(r + s[2])
    cv.imshow("noise image",image)




print("------------Hello python------------")
src = cv.imread("D:/images/lena.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
cv.imshow("image",src)

t1 = cv.getTickCount()
gaussian_noise(src) #加高斯噪声,对高斯模糊没有影响
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print("time consume : %s"%(time*1000))

dst = cv.GaussianBlur(src,(0,0),15)
cv.imshow("GaussianBlur",dst) #保留图像的主要特征

cv.waitKey(0)

cv.destroyAllWindows()

NO.10

import cv2 as cv
import numpy as np
"""
EPF 边缘(像素差很多)保留滤波
"""
def bi_demo(image):
    dst = cv.bilateralFilter(image,0,100,15)
    cv.imshow("bi_demo",dst);

def shift_demo(image):
    dst = cv.pyrMeanShiftFiltering(image,10,50) #均值
    cv.imshow("shift_demo",dst)

print("------------Hello python------------")
src = cv.imread("D:/images/lena.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
cv.imshow("image",src)
bi_demo(src)
shift_demo(src)

cv.waitKey(0)

cv.destroyAllWindows()

 

上一篇:OpenCV 图像中每个通道的图像可以分离,合并,并且可以赋值


下一篇:opencv笔记(一)