判断物体方向
#### 判断方向是否一致importcv2importnumpyasnpdefget_orientation(image):# 1. 轮廓提取graycv2.cvtColor(image,cv2.COLOR_BGR2GRAY)_,binarycv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)contours,_cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)ifnotcontours:returnNone# 2. 最小外接椭圆拟合cntmax(contours,keycv2.contourArea)ellipsecv2.fitEllipse(cnt)(center,axes,angle)ellipse# angle: 主轴与x轴的夹角0-180°# 3. 方向判定if45angle135:returnvertical# 竖直方向类似左侧元件else:returnhorizontal# 水平方向类似右侧元件if__main____name__:img_path_1r1.pngimg_path_2r2.pngimg_1cv2.imread(img_path_1)img_2cv2.imread(img_path_2)print(get_orientation(img_1))print(get_orientation(img_2))