赞
踩
#coding=gbk
import numpy as np
import matplotlib.pyplot as plt
import cv2
# 读入图像
img = cv2.imread('snake.png')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 将颜色更改为RGB(从BGR)
plt.imshow(img_rgb)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#灰度图
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
plt.imshow(binary, cmap='gray')
contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours_image = np.copy(img)
contours_image = cv2.drawContours(contours_image, contours, -1, (0,255,0), 3)
#二进制阈值图像
plt.imshow(contours_image)
def orientations(contours): angles = [] for contour in contours: if len(contour) < 5: continue # 拟合椭圆 ellipse = cv2.fitEllipse(contour) # 提取角度 angle = ellipse[2] angles.append(angle) return angles # ---------------------------------------------------------- # # 打印方向值 angles = orientations(contours) print('Angles of each contour (in degrees): ' + str(angles))
Angles of each contour (in degrees): [92.56619262695312, 0.0, 0.0, 96.2242660522461, 47.50788879394531, 1.298294186592102, 0.0029462939128279686]
## TODO: 完成此功能,以便 ## 它会返回原始图像的新裁剪版本 def left_hand_crop(image, selected_contour): """ Left hand crop :参数图像:原始图像 :参数selectec_contour:将用于裁剪的轮廓 :返回值: cropped_image, 左手周围的裁剪图像 """ ## TODO: 检测左手轮廓的边界矩形 x, y, w, h = cv2.boundingRect(selected_contour) box_image = cv2.rectangle(contours_image, (x,y), (x+w,y+h), (200,0,200),2) ## TODO: 使用边界矩形的尺寸裁剪图像 # 复制图像进行裁剪 cropped_image = np.copy(box_image) cropped_image = box_image[y: y + h, x: x + w] return cropped_image ## TODO: 从列表中选择左侧轮廓 ## 替换此值 selected_contour = contours[1] # ---------------------------------------------------------- # # 如果选择了轮廓 if(selected_contour is not None): # 调用带有该轮廓的裁剪函数作为参数 cropped_image = left_hand_crop(img, selected_contour) plt.imshow(cropped_image)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。