camera_driver.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 # Copyright 2019 The UFACTORY Inc. All Rights Reserved.
4 #
5 # Software License Agreement (BSD License)
6 #
7 # Author: Jimy Zhang <jimy.zhang@ufactory.cc> <jimy92@163.com>
8 # =============================================================================
9 
10 import cv2
11 import numpy as np
12 import math
13 import time
14 
15 class CameraDriver(object):
16  def __init__(self, video_port):
17  self.cameraCapture = cv2.VideoCapture(video_port)
18  self.xy2=[1,1]
19  self.state = 0
20 
21  def close(self):
22  cv2.destroyAllWindows()
23 
24  def get_image(self):
25  cv2.waitKey(1)
26  success, image_src = self.cameraCapture.read()
27  if success:
28  return image_src
29  else:
30  print("ERROR: cameraCapture.read()")
31  self.state = -1
32 
33  # 识别image中的蓝色物体
34  # pose_mid:蓝色物体的像素坐标
35  # s:蓝色物体的体积
36  # show_image:1->显示过程图片;0->不显示过程图片
37  def identify_colour(self, image, pose_mid, s, show_image=0):
38  if self.state == -1:
39  return
40 
41  image2_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
42 
43  LowerBlue = np.array([90, 100, 100])
44  UpperBlue = np.array([130, 255, 255])
45  mask = cv2.inRange(image2_hsv, LowerBlue, UpperBlue)
46  image3_hsv = cv2.bitwise_and(image2_hsv, image2_hsv, mask=mask)
47  image4_gry = image3_hsv[:,:,0]
48 
49  blurred = cv2.blur(image4_gry, (9, 9))
50  (_, thresh) = cv2.threshold(blurred, 90, 255, cv2.THRESH_BINARY)
51  kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 25))
52  closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
53 
54  closed = cv2.erode(closed, None, iterations=4)
55  closed = cv2.dilate(closed, None, iterations=4)
56  if show_image == 1:
57  cv2.imshow('win6_bin', closed)
58 
59  aaa, contours, hier = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
60  i = 0
61  for c in contours:
62  x, y, w, h = cv2.boundingRect(c)
63  rect = cv2.minAreaRect(c)
64  box = cv2.boxPoints(rect)
65  box =np.int0(box)
66  cv2.drawContours(image, [box], 0, (0, 0, 255), 3)
67 
68  pose_mid[i] = [(box[0][0] + box[2][0])/2, (box[0][1] + box[2][1])/2]
69  w = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][1])**2)
70  h = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][1])**2)
71  s[i] = w * h
72  s.sort(reverse=True)
73  i = i + 1
74 
75  if show_image == 1:
76  cv2.imshow("Image", image)
def __init__(self, video_port)
def identify_colour(self, image, pose_mid, s, show_image=0)


xarm_device
Author(s):
autogenerated on Sat May 8 2021 02:51:20