OpenCV-Python练习笔记(一)

首页 / 学习笔记 / 正文

练习一:

import cv2
img = cv2.imread("D:\sb\meixi.png")

# px = img[100, 90]
# print(px)  # [103 98 197]

# 只获取蓝色blue通道的值
# px_blue = img[100, 90, 0]
# print(px_blue)  # 103

img1 = img[100:500, 300:600]
cv2.imshow("img1",img1)
cv2.waitKey(0)
px_red = img1[100,90,2]
print(px_red)
# 截取脸部ROI
# face = img[100:200, 115:188]
# cv2.imshow('face', face)
# cv2.waitKey(0)

flags = [i for i in dir(cv2) if i.startswith('COLOR_')]
print(flags)

练习二:

#颜色空间转换
import cv2
#
# img = cv2.imread('D:\sb\meixi.png')
# # 转换为灰度图
# img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#
# cv2.imshow('img', img)
# cv2.imshow('gray', img_gray)
# cv2.waitKey(0)

import numpy as np

capture = cv2.VideoCapture(1)

# 蓝色的范围,不同光照条件下不一样,可灵活调整
lower_blue = np.array([100, 110, 110])
upper_blue = np.array([130, 255, 255])

while(True):
    # 1.捕获视频中的一帧
    ret, frame = capture.read()

    # 2.从BGR转换到HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # 3.inRange():介于lower/upper之间的为白色,其余黑色
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # 4.只保留原图中的蓝色部分
    res = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)

    if cv2.waitKey(1) == ord('q'):
        break

练习三:

#阈值分割
import cv2

# 灰度图读入
img = cv2.imread('gray_face11.jpg', 0)

# 阈值分割
ret, th = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
cv2.imshow('thresh', th)

cv2.waitKey(0)
打赏
评论区
头像