opencv-python提取特定颜色、面积、圆度、惯性和凸度的代码
时间: 2023-07-10 10:22:55 浏览: 216
Python Opencv提取图片中某种颜色组成的图形的方法
5星 · 资源好评率100%
以下是使用OpenCV-Python库提取特定颜色、面积、圆度、惯性和凸度的代码示例:
1. 提取特定颜色的特征点
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg')
# 将图像转换为HSV颜色空间
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 设定颜色范围
lower_color = np.array([0, 100, 100])
upper_color = np.array([10, 255, 255])
# 提取特定颜色区域
mask = cv2.inRange(hsv, lower_color, upper_color)
# 寻找特定颜色的特征点
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
keypoints = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
keypoints.append(cv2.KeyPoint(x=x, y=y, _size=w*h))
```
2. 提取特定面积、圆度、惯性和凸度的特征点
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 寻找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 提取特定面积、圆度、惯性和凸度的特征点
keypoints = []
for contour in contours:
area = cv2.contourArea(contour)
if area < 100 or area > 1000:
continue
perimeter = cv2.arcLength(contour, True)
circularity = 4*np.pi*(area/(perimeter**2))
if circularity < 0.7:
continue
x, y, w, h = cv2.boundingRect(contour)
if w/h > 2 or h/w > 2:
continue
M = cv2.moments(contour)
if M['m00'] == 0:
continue
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
inertia = cv2.moments(contour, True)
if inertia['nu20'] + inertia['nu02'] < 0.1:
continue
hull = cv2.convexHull(contour)
hull_area = cv2.contourArea(hull)
if area/hull_area < 0.5:
continue
keypoints.append(cv2.KeyPoint(x=cx, y=cy, _size=area))
```
这些代码示例仅供参考,实际应用中需要根据具体的需求进行调整。
阅读全文