OpenCV+Python
安装 OpenCV:
Python:直接 pip install opencv-python
(核心库)和 opencv-contrib-python
(扩展功能)。
pip install opencv-python
pip install opencv-contrib-python
验证安装:
import cv2
print(cv2.__version__) # 输出版本号
以下代码来源于:链接
if __name__ == '__main__':# 读取图像image = cv2.imread('1.png')# 显示图像# cv2.imshow('Image', image)gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)print('gray_image = ', gray_image)# cv2.imshow('Image', gray_image)edges = cv2.Canny(gray_image, threshold1=50, threshold2=150)print('edges = ', edges)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))dilated = cv2.dilate(edges, kernel, iterations=1)cv2.imshow('Image', dilated)cv2.waitKey(0)cv2.destroyAllWindows()# 特征检测# image = cv2.imread('3.png')# orb = cv2.ORB_create()# keypoints, descriptors = orb.detectAndCompute(image, None)# image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(0, 255, 0))# cv2.imshow('Keypoints', image_with_keypoints)# cv2.waitKey(0)# cv2.destroyAllWindows()# 人脸检测# image = cv2.imread('3.png')# face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)# for (x, y, w, h) in faces:# cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)# cv2.imshow('Faces', image)# cv2.waitKey(0)# cv2.destroyAllWindows()# 交通标志识别# image = cv2.imread('5.png')## gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# edges = cv2.Canny(gray_image, threshold1=50, threshold2=150)## kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))# dilated = cv2.dilate(edges, kernel, iterations=1)# contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# for contour in contours:# if cv2.contourArea(contour) > 100:# x, y, w, h = cv2.boundingRect(contour)# cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)## cv2.imshow('Traffic Sign Detection', image)# cv2.waitKey(0)# cv2.destroyAllWindows()# 显示图像# image = cv2.imread('3.png')# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# # 下面这行代码效果等价于上面两行代码# gray_scare_image = cv2.imread('3.png', cv2.IMREAD_GRAYSCALE)# ret, binary = cv2.threshold(gray_scare_image, 127, 255, cv2.THRESH_BINARY)# ret_inv, binary_inv = cv2.threshold(gray_scare_image, 127, 255, cv2.THRESH_BINARY_INV)# cv2.imshow('gray_image', gray_image)# cv2.imshow('gray_scare_image', gray_scare_image)# cv2.imshow('binary', binary)# cv2.imshow('binary_inv', binary_inv)# cv2.waitKey(0)# cv2.destroyAllWindows()
这个链接也看了:链接