本实验使用的相机为realsense系列,什么相机不重要,拿到图像数据流即可
实现功能:
1.实时显示图像
2.框出图像内识别到的最大轮廓,并绘制中心点
3.得到最大轮廓物体的旋转角(这个是我后续需要的数据,代码就一块贴上了)
先上效果图:
(受灯光影响还是挺大的,调整二值化时的参数应当是一种解决措施)
ps:找的gif录制像素感人,555
上代码:
流程:
读图像流–>高斯滤波–>转灰度–>二值化–>开运算–>轮廓拟合、绘制–>显示
# -*- coding: utf-8 -*-
import pyrealsense2 as rs
import numpy as np
import cv2
import os
import time
import sys
# Configure color streams
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
#start
pipeline.start(config)
try:
while True:
frames = pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
continue
color_image=np.asanyarray(color_frame.get_data())
#GausBlur
Gausablur=cv2.GaussianBlur(color_image,(5,5),1.5)
#To_gray_
gray=cv2.cvtColor(Gausablur,cv2.COLOR_BGR2GRAY)
#2vlaue
ret,binary=cv2.threshold(gray,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
#open math
kernel=np.ones((5,5),np.uint8)
opening=cv2.morphologyEx(binary,cv2.MORPH_OPEN,kernel, iterations=3)#五次开运算
#轮廓拟合
im2, contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
area=[]
for i in contours:
area.append(cv2.contourArea(i))
for i in contours:
if cv2.contourArea(i)==max(area):
rect = cv2.minAreaRect(i)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(color_image,[box],0,(0,0,255),3) #画矩形框
#图像轮廓及中心点坐标
M = cv2.moments(i)# 计算第一条轮廓的各阶矩,字典形式
#print(M)
center_x = int(M['m10']/M['m00'])
center_y = int(M['m01']/M['m00'])
data_xy=[center_x,center_y]
#print('center_x:',center_x)
#print('center_y:',center_y)
cv2.circle(color_image,(center_x,center_y),7,128,-1)#绘制中心点
str1 = '(' + str(center_x)+ ',' +str(center_y) +')' #把坐标转化为字符串
cv2.putText(color_image,str1,(center_x-50,center_y+40),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)#绘制坐标点位
#get 偏转角
p_angel=rect[2]
width=rect[1][0]
height=rect[1][1]
global angle
if width<height:
angle=90-p_angel
else:
angle=p_angel
cv2.imshow('Gaus',color_image)
key=cv2.waitKey(1)
if key==27:
sys.exit()
#stop
finally:
pipeline.stop()