opencv-python练习实例

一、作者有话说

本来想出个opencv-python的环境配置的,但最近天天配环境,配的我头大,就算了,下个周再出环境配置相关的问题(约定一下,一个月不能配环境超过两次),我最近在学opencv-python,把自己平时做的练习题发过来给大家看一看,也算是自己记的笔记,还是那句话,本人现在水平太低,写不出什么好东西,只是分享一下自己的学习过程,更加有学习的动力而已。

例1

代码:

import cv2 as cv


img = cv.imread("E:/images/kenan.jpeg", cv.IMREAD_COLOR) # 读取图片
cv.imshow('input image', img)												 		# 显示图片
cv.imwrite("test.jpg", img) 	# 保存图片
cv.waitKey()

cv.destoryAllWindows()

效果:
图太大了。。。然后会保存一个test.jpg的图片
opencv-python练习实例_第1张图片

例2、创建一个video

import cv2

cap = cv2.VideoCapture(0)
while True:
	# ret是True或者false,frame是目标图片
    ret, frame = cap.read()
    # 这里是未处理的视频
    cv2.imshow('frame', frame)
	#灰度视频
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)
	#将视频左右对调
    frame = cv2.flip(frame, 1)
    cv2.imshow("video", frame)
    #按q退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

例3显示图片,并输出图片的type,size等

(明天放截图)

import cv2 as cv
import numpy as np


def get_image_info(image):
    print(type(image))
    print(image.shape)
    print(image.size)
    print(image.dtype)
    pixel_data = np.array(image)
    print(pixel_data)


src = cv.imread("E:/images/kenan.jpeg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
get_image_info(src)
cv.waitKey(0)

cv.destroyAllWindows()

例4、寻找视频中的绿色(视频自己录)

opencv-python练习实例_第2张图片

import cv2 as cv
import numpy as np


def extrace_object_demo():
    capture = cv.VideoCapture("E:/video/green.mp4")
    while True:
        ret, frame = capture.read()
        if not ret:
            break
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        lower_hsv = np.array([37, 43, 46])
        upper_hsv = np.array([77, 255, 255])
        mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
        dst = cv.bitwise_and(frame, frame, mask=mask)
        cv.imshow("video", frame)
        cv.imshow("mask", dst)
        c = cv.waitKey(40)
        if c == 27:
            break


src = cv.imread("E:/images/test3.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
extrace_object_demo()
cv.waitKey()

cv.destoryAllWindows()

例5、保存视频文件

import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 24.0, (640, 480))

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        frame = cv2.flip(frame, 1)  # 沿x轴旋转
        out.write(frame)
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()

out.release()
cv2.destroyAllWindows()

你可能感兴趣的:(opencv-python)