OpenCV基础

1. 基础入门:OpenCV概念与安装

a. OpenCV简介

OpenCV(Open Source Computer Vision Library)是一个开源的计算机视觉库,广泛应用于图像和视频处理、计算机视觉、机器学习等领域。

b. 安装OpenCV
  • Python安装:

    pip install opencv-python
    pip install opencv-python-headless  # 如果不需要GUI功能
    
  • C++安装:
    你可以参考OpenCV官网提供的安装指南,进行从源码编译或使用预编译的库进行安装。

c. OpenCV基本结构
  • 读取与显示图像:
    使用cv2.imread()读取图像,cv2.imshow()显示图像,cv2.waitKey()暂停,cv2.destroyAllWindows()关闭窗口。

    import cv2
    image = cv2.imread('image.jpg')
    cv2.imshow('Image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  • 保存图像:

    cv2.imwrite('output.jpg', image)
    
  • 基础图像操作:

    • 获取图像尺寸:image.shape
    • 访问图像像素:image[y, x]
    • 图像裁剪:cropped_image = image[y1:y2, x1:x2]

2. 图像处理:核心操作

a. 基本操作
  • 灰度转换:

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
  • 图像平滑:

    • 均值滤波:cv2.blur(image, (5, 5))
    • 高斯模糊:cv2.GaussianBlur(image, (5, 5), 0)
  • 图像锐化:
    使用卷积核进行锐化:

    kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]])
    sharpened = cv2.filter2D(image, -1, kernel)
    
  • 图像边缘检测:

    • Canny边缘检测:
    edges = cv2.Canny(image, 100, 200)
    
b. 图像变换
  • 旋转、缩放、平移:
    # 旋转
    rows, cols = image.shape[:2]
    M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1)
    rotated_image = cv2.warpAffine(image, M, (cols, rows))
    
    # 缩放
    resized_image = cv2.resize(image, (width, height))
    
    # 平移
    M = np.float32([[1, 0, 100], [0, 1, 50]])  # x平移100,y平移50
    translated_image = cv2.warpAffine(image, M, (cols, rows))
    
c. 形态学操作
  • 膨胀与腐蚀:

    kernel = np.ones((5,5), np.uint8)
    dilated = cv2.dilate
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值