a | b/ObjectDetection.py | ||
---|---|---|---|
1 | import cv2 |
||
2 | import datetime |
||
3 | import time |
||
4 | import numpy |
||
5 | from multiprocessing import shared_memory |
||
6 | |||
7 | def detect(frame): |
||
8 | #Convert source image to hsv image |
||
9 | hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) |
||
10 | |||
11 | #Define the range of color blue |
||
12 | lower_boarder = numpy.array([110, 50, 50]) |
||
13 | upper_boarder = numpy.array([130, 255, 255]) |
||
14 | |||
15 | #Show the blue values in white, all others black |
||
16 | mask = cv2.inRange(hsv, lower_boarder, upper_boarder) |
||
17 | |||
18 | #Get the treshold and contours of the blue elements |
||
19 | ret, threshed_img = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY) |
||
20 | contours, hier = cv2.findContours(threshed_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) |
||
21 | |||
22 | #Bounding rect around every blue element and get coordinates |
||
23 | s='' |
||
24 | for c in contours: |
||
25 | (x,y,w,h) = cv2.boundingRect(c) |
||
26 | pt = (x, y+h) |
||
27 | cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 1) |
||
28 | s += str(pt) + ' ' |
||
29 | #Prevent to many contours in share memory sting |
||
30 | if len(s) > 50: |
||
31 | break |
||
32 | return s |
||
33 | |||
34 | #Get the image of camera |
||
35 | def getVideoFrame(): |
||
36 | cam = cv2.VideoCapture(0) |
||
37 | ret_val, frame = cam.read() |
||
38 | cv2.imshow("frame", frame) |
||
39 | return frame |
||
40 | |||
41 | def shareMemory(memName, memString, memSize, memTime): |
||
42 | #Create new shared memory object |
||
43 | shm = shared_memory.SharedMemory(name=memName, create=True, size=memSize) |
||
44 | #Encode string in utf-8 |
||
45 | encoded=memString.encode('utf-8') |
||
46 | #Convert string to bytearray |
||
47 | bArr = bytearray(encoded) |
||
48 | #Write every single element in shared memory buffer |
||
49 | if len(bArr) < memSize: |
||
50 | for i in range(len(bArr)): |
||
51 | shm.buf[i] = bArr[i] |
||
52 | #Delay to read the memory in other application, before close |
||
53 | time.sleep(memTime) |
||
54 | shm.close() |
||
55 | |||
56 | if __name__ == '__main__': |
||
57 | #Get the image of an file |
||
58 | frame = cv2.imread("Bubbles_640x480.jpg") |
||
59 | #To get video call getVideoFrame() in a loop |
||
60 | #Add a time stamp to the string |
||
61 | s = detect(frame) + str(datetime.datetime.now()) |
||
62 | shareMemory(memName='MySharedMemory', memString=s, memSize=100, memTime=60) |