计算机视觉入门:从零开始掌握图像处理与识别基础 计算机视觉(Computer Vision)是人工智能领域的一个重要分支,旨在让计算机能够“看懂”图像和视频内容。随着深度学习技术的发展,计算机视觉已在自动驾驶、医疗影像分析、安防监控等领域广泛应用。本文将带你从零开始学习计算机视觉的基础知识,并通过实际代码示例演示如何实现常见的图像处理任务。
👋 一、计算机视觉基础概念 1.1 什么是计算机视觉? 计算机视觉是研究如何让计算机从图像或视频中获取信息、理解内容并做出决策的科学。它与图像处理密切相关,但更侧重于对图像内容的分析和理解。
1.2 基本任务类型 计算机视觉的主要任务包括:
图像分类:识别图像中的主要对象 目标检测:定位并识别图像中的多个对象 图像分割:将图像划分为多个区域或对象 特征提取:从图像中提取有意义的特征 🚀 二、环境搭建与工具准备 在开始实践前,我们需要搭建开发环境。推荐使用Python和以下库:
1 2 3 4 5 pip install opencv-python pip install numpy pip install matplotlib pip install tensorflow pip install scikit-learn
三、图像处理基础 3.1 读取和显示图像 1 2 3 4 5 6 7 8 9 10 11 12 13 import cv2import matplotlib.pyplot as pltimage = cv2.imread('sample.jpg' ) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image_rgb) plt.axis('off' ) plt.show()
3.2 图像基本操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 print ("图像形状:" , image.shape)print ("图像高度:" , image.shape[0 ])print ("图像宽度:" , image.shape[1 ])print ("通道数:" , image.shape[2 ])resized_image = cv2.resize(image, (256 , 256 )) (h, w) = image.shape[:2 ] center = (w // 2 , h // 2 ) matrix = cv2.getRotationMatrix2D(center, 45 , 1.0 ) rotated_image = cv2.warpAffine(image, matrix, (w, h)) cv2.imwrite('rotated_image.jpg' , rotated_image)
👋 四、图像预处理技术 4.1 灰度转换 1 2 3 4 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) plt.imshow(gray_image, cmap='gray' ) plt.show()
4.2 图像二值化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 _, binary_image = cv2.threshold(gray_image, 127 , 255 , cv2.THRESH_BINARY) adaptive_binary = cv2.adaptiveThreshold( gray_image, 255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11 , 2 ) plt.figure(figsize=(10 , 5 )) plt.subplot(1 , 2 , 1 ) plt.imshow(binary_image, cmap='gray' ) plt.title('简单阈值' ) plt.subplot(1 , 2 , 2 ) plt.imshow(adaptive_binary, cmap='gray' ) plt.title('自适应阈值' ) plt.show()
4.3 图像滤波 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 blurred = cv2.GaussianBlur(image, (5 , 5 ), 0 ) median = cv2.medianBlur(image, 5 ) edges = cv2.Canny(image, 100 , 200 ) plt.figure(figsize=(15 , 5 )) plt.subplot(1 , 3 , 1 ) plt.imshow(cv2.cvtColor(blurred, cv2.COLOR_BGR2RGB)) plt.title('高斯模糊' ) plt.subplot(1 , 3 , 2 ) plt.imshow(cv2.cvtColor(median, cv2.COLOR_BGR2RGB)) plt.title('中值滤波' ) plt.subplot(1 , 3 , 3 ) plt.imshow(edges, cmap='gray' ) plt.title('边缘检测' ) plt.show()
💡 五、特征提取与描述 5.1 Harris角点检测 1 2 3 4 5 6 7 8 9 10 11 12 13 14 gray = np.float32(gray_image) dst = cv2.cornerHarris(gray, 2 , 3 , 0.04 ) dst = cv2.dilate(dst, None ) image_with_corners = image.copy() image_with_corners[dst > 0.01 * dst.max ()] = [0 , 0 , 255 ] plt.imshow(cv2.cvtColor(image_with_corners, cv2.COLOR_BGR2RGB)) plt.title('Harris角点检测' ) plt.show()
5.2 SIFT特征提取 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 sift = cv2.SIFT_create() keypoints, descriptors = sift.detectAndCompute(gray_image, None ) image_with_keypoints = cv2.drawKeypoints( image, keypoints, None , flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ) plt.imshow(cv2.cvtColor(image_with_keypoints, cv2.COLOR_BGR2RGB)) plt.title('SIFT特征点' ) plt.show()
六、图像分类实战 下面我们使用预训练的深度学习模型进行图像分类。
6.1 使用预训练模型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from tensorflow.keras.applications import ResNet50from tensorflow.keras.preprocessing import imagefrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictionsimport numpy as npmodel = ResNet50(weights='imagenet' ) img_path = 'sample.jpg' img = image.load_img(img_path, target_size=(224 , 224 )) x = image.img_to_array(img) x = np.expand_dims(x, axis=0 ) x = preprocess_input(x) predictions = model.predict(x) decoded_predictions = decode_predictions(predictions, top=3 )[0 ] print ("预测结果:" )for i, (imagenet_id, label, score) in enumerate (decoded_predictions): print (f"{i+1 } : {label} ({score:.2 f} )" )
6.2 实时摄像头图像分类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import cv2import numpy as npfrom tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictionsmodel = MobileNetV2(weights='imagenet' ) cap = cv2.VideoCapture(0 ) while True : ret, frame = cap.read() if not ret: break input_frame = cv2.resize(frame, (224 , 224 )) input_array = np.expand_dims(input_frame, axis=0 ) input_array = preprocess_input(input_array) predictions = model.predict(input_array) label = decode_predictions(predictions, top=1 )[0 ][0 ][1 ] cv2.putText(frame, f'Prediction: {label} ' , (10 , 30 ), cv2.FONT_HERSHEY_SIMPLEX, 1 , (0 , 255 , 0 ), 2 ) cv2.imshow('Real-time Classification' , frame) if cv2.waitKey(1 ) & 0xFF == ord ('q' ): break cap.release() cv2.destroyAllWindows()
🚀 七、目标检测入门 7.1 使用OpenCV进行人脸检测 1 2 3 4 5 6 7 8 9 10 11 12 13 14 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) faces = face_cascade.detectMultiScale(gray_image, 1.1 , 4 ) image_with_faces = image.copy() for (x, y, w, h) in faces: cv2.rectangle(image_with_faces, (x, y), (x+w, y+h), (255 , 0 , 0 ), 2 ) plt.imshow(cv2.cvtColor(image_with_faces, cv2.COLOR_BGR2RGB)) plt.title('人脸检测结果' ) plt.show()
八、下一步学习建议 深入学习深度学习 :掌握CNN、RNN等神经网络结构学习高级计算机视觉任务 :如图像分割、目标跟踪、3D重建等实践项目 :尝试完成实际项目,如车牌识别、人脸识别系统等阅读论文 :关注CVPR、ICCV等顶级会议的最新研究成果参与开源项目 :在GitHub上寻找相关项目参与贡献🚀 总结 本文介绍了计算机视觉的基础知识和实践技巧,从图像处理基础到深度学习应用,涵盖了入门所需的核心内容。通过实际的代码示例,你可以快速上手并开始自己的计算机视觉项目。记住,实践是最好的学习方式,不断尝试和实验将帮助你更好地掌握这一领域的知识。
计算机视觉是一个快速发展的领域,保持学习和实践的态度至关重要。祝你在这条学习道路上取得丰硕的成果!
[up主专用,视频内嵌代码贴在这]
零点119官方团队
一站式科技资源平台 | 学生/开发者/极客必备
本文由零点119官方团队原创,转载请注明出处。文章ID: 874e2f32