Python快速学习opencv

Posted Harris-H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python快速学习opencv相关的知识,希望对你有一定的参考价值。

Python快速学习opencv

1.安装opencv-python

pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

2.打开图片并在窗口显示

    img = cv2.imread('Resources/lena.jpg')
    cv2.imshow('output', img)
    cv2.waitKey(0)

3.播放视频

    cap = cv2.VideoCapture('Resources/video.mp4')
    while True:
        success, img = cap.read()
        cv2.imshow('video', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):		# 按q键关闭
            break

4.显示摄像头

    cap = cv2.VideoCapture(0)  # 默认是用户的摄像头
    cap.set(3, 640)  # 设置宽高
    cap.set(4, 480)
    cap.set(10, 100)  # 设置亮度
    while True:
        success, img = cap.read()
        cv2.imshow('video', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):  # 按q键关闭
            break

5.图像灰度处理、高斯模糊、边缘处理、膨胀处理、腐蚀处理

kernel = np.ones((5, 5), np.uint8)
if __name__ == '__main__':
    img = cv2.imread('Resources/lena.jpg')
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 灰度处理
    imgBlur = cv2.GaussianBlur(imgGray, (7, 7), 0)  # 高斯模糊
    imgCanny = cv2.Canny(img, 150, 200)  # 边缘化
    imgDialation = cv2.dilate(imgCanny, kernel, iterations=1)  # 膨胀处理
    imgEroded = cv2.erode(imgDialation, kernel, iterations=1) # 腐蚀处理
    cv2.imshow('Img Gray', imgGray)
    cv2.imshow('Img Blur', imgBlur)
    cv2.imshow('Img Canny', imgCanny)
    cv2.imshow('Img Dialation', imgDialation)
    cv2.imshow('Img imgEroded', imgEroded)
    cv2.waitKey(0)

6.调整图像

    img = cv2.imread('Resources/lena.jpg')
    print(img.shape)  # 打印的是高和宽和频道数量
    imgResize = cv2.resize(img, (300, 100))  # 调整宽为300 高为100

    imgCropped = img[0:200, 200:300]  # 高从0到200 宽从 200到300
    print(imgResize.shape)
    cv2.imshow('imgCropped', imgCropped)
    cv2.imshow('img', img)
    cv2.waitKey(0)

7.绘制图形

    img = np.zeros((512, 512, 3), np.uint8)
    img[:] = 255, 0, 0  # 修改图像颜色为蓝色(BGR)
    cv2.line(img, (0, 0), (200, 200), (0, 255, 0), 3)  # 画一条绿线起点是(0,0) 终点是(200,200) 颜色是绿色 厚度是3
    cv2.rectangle(img, (0, 0), (100, 100), (0, 0, 255), cv2.FILLED)  # 填充红色矩形
    cv2.circle(img, (200, 100), 30, (255, 255, 0), 5)  # 填充圆形
    cv2.putText(img, 'This is a Text', (250, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 150, 0), 3)
    cv2.imshow('img', img)
    cv2.waitKey(0)

8.截取特定位置的图片

import cv2
import numpy as np

img = cv2.imread("Resources/cards.jpg")

width, height = 250, 350
pts1 = np.float32([[111, 219], [287, 188], [154, 482], [352, 440]])  # 需要截取的区域(左上,右上,左下,右下)
pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]])  # 转换后的矩阵区域
matrix = cv2.getPerspectiveTransform(pts1, pts2)  # 创建转换矩阵
imgOutput = cv2.warpPerspective(img, matrix, (width, height))  # 导出转换后的图片

cv2.imshow("Image", img)
cv2.imshow("Output", imgOutput)
print(imgOutput.shape)
cv2.waitKey(0)

9.堆叠图像

import cv2
import numpy as np


def stackImages(scale, imgArray):  # 将图像堆叠的函数
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range(0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape[:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]),
                                                None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y] = cv2.cvtColor(imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank] * rows
        hor_con = [imageBlank] * rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor = np.hstack(imgArray)
        ver = hor
    return ver


img = cv2.imread('Resources/lena.png')
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

imgStack = stackImages(0.5, ([img, imgGray, img], [img, img, img]))  # 2*3进行堆叠

# imgHor = np.hstack((img,img))	 水平堆叠
# imgVer = np.vstack((img,img))	 竖直堆叠
#
# cv2.imshow("Horizontal",imgHor)
# cv2.imshow("Vertical",imgVer)
cv2.imshow("ImageStack", imgStack)

cv2.waitKey(0)

10.通过检测图片颜色和定义追踪栏获取指定内容

import cv2
import numpy as np

def empty(a):
    pass

def stackImages(scale,imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank]*rows
        hor_con = [imageBlank]*rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        ver = hor
    return ver



path = 'Resources/lambo.png'
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",19,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",110,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",240,255,empty)
cv2.createTrackbar("Val Min","TrackBars",153,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)

while True:
    img = cv2.imread(path)
    imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    h_min = cv2.getTrackbarPos("Hue Min","TrackBars")
    h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
    s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
    s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
    v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
    v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
    print(h_min,h_max,s_min,s_max,v_min,v_max)
    lower = np.array([h_min,s_min,v_min])
    upper = np.array([h_max,s_max,v_max])
    mask = cv2.inRange(imgHSV,lower,upper)
    imgResult = cv2.bitwise_and(img,img,mask=mask)


    # cv2.imshow("Original",img)
    # cv2.imshow("HSV",imgHSV)
    # cv2.imshow("Mask", mask)
    # cv2.imshow("Result", imgResult)

    imgStack = stackImages(0.6,([img,imgHSV],[mask,imgResult]))
    cv2.imshow("Stacked Images", imgStack)

    cv2.waitKey(1)

11.图形形状识别

import cv2
import numpy as np


def stackImages(scale, imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range(0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0]

以上是关于Python快速学习opencv的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV 机器视觉入门精选 100 题(附 Python 代码)

Python黑科技:50行代码运用Python+OpenCV实现人脸追踪+详细教程+快速入门+图像识

Python黑科技:50行代码运用Python+OpenCV实现人脸追踪+详细教程+快速入门+图像识

Python黑科技:50行代码运用Python+OpenCV实现人脸追踪+详细教程+快速入门+图像识

OpenCV 学习笔记(颜色直方图计算 calcHist)

python 机器学习有用的代码片段