Hello i am a college student and have a little problem with my code. i want to give 3 seconds wait time in my code after a motorcycle get detected on the system, after that a sound came out. i try to manipulate the time but its not working. could anybody help with my code
import cv2
import numpy as np
import pygame
import datetime as dt
from pygame import mixer
import time
#=============== Variable Mouse ==================#
drawing = False
point1 = ()
point2 = ()
drawingTwo = False
pointTwo_1 = ()
pointTwo_2 = ()
Mouse_count = False
#================================================#
def mouse_drawing(event, x, y, flags, params):
global point1, point2, drawing
global pointTwo_1, pointTwo_2, drawingTwo, Mouse_count
#----------Mouse 1-------
if Mouse_count == False:
if event == cv2.EVENT_LBUTTONDOWN:
if drawing is False:
drawing = True
point1 = (x, y)
#else:
#drawing = False
elif event == cv2.EVENT_MOUSEMOVE:
if drawing is True:
point2 = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
Mouse_count = True
#----------Mouse 2-------#
if Mouse_count == True:
if event == cv2.EVENT_LBUTTONDOWN:
if drawingTwo is False:
drawingTwo = True
pointTwo_1 = (x, y)
elif event == cv2.EVENT_MOUSEMOVE:
if drawingTwo is True:
pointTwo_2 = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
if drawingTwo is True:
drawingTwo = False
Mouse_count = False
#================================================#
lastTime = dt.datetime.now()
currentTime = dt.datetime.now()
#Make Sound
pygame.mixer.init()
#create VideoCapture object and read from video file
cap = cv2.VideoCapture('test13.mp4')
cv2.namedWindow("Detecion motor")
cv2.setMouseCallback("Detecion motor", mouse_drawing)
while True:
ret, frame = cap.read()
car_cascade = cv2.CascadeClassifier('cascade11.xml')
#============================== ROI One ============================#
if point1 and point2:
#Rectangle marker
r = cv2.rectangle(frame, point1, point2, (100, 50, 200), 5)
frame_ROI = frame[point1[1]:point2[1],point1[0]:point2[0]]
#------------------Detect car ROI-------------------#
if drawing is False:
#convert video into gray scale of each frames
ROI_grayscale = cv2.cvtColor(frame_ROI, cv2.COLOR_BGR2GRAY)
#detect cars in the video
cars_ROI = car_cascade.detectMultiScale(ROI_grayscale, 1.1, 3)
if len(cars_ROI) > 0:
if (currentTime-lastTime).seconds > 3:
lastTime = dt.dateTime.now()
sound = mixer.Sound('sirine2.wav')
sound.play()
for (x,y,w,h) in cars_ROI:
cv2.rectangle(frame_ROI,(x,y),(x+w,y+h),(0,255,0),2)
currentTime = dt.datetime.now()
#cv2.putText(frame_ROI, "Jumlah Motor : " + str(cars_ROI.shape[0]), (10,frame_ROI.shape[0] -25), cv2.FONT_HERSHEY_TRIPLEX, 0.5,(0,255,0), 1)
#-------------------------------------------------#
#==================================================================#
#============================== ROI Two ============================#
#==================================================================#
cv2.imshow("Detecion motor", frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
i dont know i already try use time.sleep but its just make my system delay not solve my problem
Your indention is wrong in your example this:
if (currentTime-lastTime).seconds > 3:
lastTime = dt.dateTime.now()
sound = mixer.Sound('sirine2.wav')
sound.play()
This is gonna play the sound every time a motorcycle is detected and your just reseting the lasttime variable. Instead do this :
if (currentTime-lastTime).seconds > 3:
lastTime = dt.dateTime.now()
sound = mixer.Sound('sirine2.wav')
sound.play()
Related
so i'm using opencv and i want to make a sort of selection tool but the problem is can't make the rectangle transparent. here's the code:
import numpy as np
import cv2 as cv
drawing = False
def draw_rec(event,x,y,flags,param):
global ix,iy,drawing
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv.EVENT_LBUTTONUP:
drawing = False
cv.rectangle(img,(ix,iy),(x,y),(0,0,0),-1)
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 5)
img = cv.imread('baboon.jpg', -1)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_rec)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
The first mistake in the code is:
elif event == cv.EVENT_LBUTTONUP:
drawing = False
cv.rectangle(img,(ix,iy),(x,y),(0,0,0),-1)
The -1 parameter means to fill the rectangle. source If we change -1 to 1:
From my point of view, the result is not satisfactory. The multiple rectangle display is caused by the mouse_movement.
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 5)
Each time the mouse moves, the rectangle will be drawn. I think it is better if we draw when the mouse movement finishes:
Code:
import numpy as np
import cv2 as cv
drawing = False
def draw_rec(event,x,y,flags,param):
global ix,iy,drawing
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv.EVENT_LBUTTONUP:
drawing = False
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),5)
img = cv.imread('27BR1.jpg', -1)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_rec)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
I am trying to draw two zones by clicking by mouse events and i thought about using two threads and a lock and here is my code :
import numpy as np
import cv2
from threading import Thread, RLock
CANVAS_SIZE = (600,800)
FINAL_LINE_COLOR = (255, 255, 255)
WORKING_LINE_COLOR = (127, 127, 127)
verrou = RLock()
class ZoneDrawer(Thread):
def __init__(self, window_name):
Thread.__init__(self)
self.window_name = window_name
self.done = False
self.current = (0, 0)
self.points = []
def on_mouse(self, event, x, y, buttons, user_param):
if event == cv2.EVENT_MOUSEMOVE:
self.current = (x, y)
elif event == cv2.EVENT_LBUTTONDOWN:
print("Adding point #%d with position(%d,%d)" % (len(self.points), x, y))
self.points.append((x, y))
elif event == cv2.EVENT_RBUTTONDOWN:
self.done = True
def run(self):
cv2.namedWindow(self.window_name)
cv2.imshow(self.window_name, np.zeros(CANVAS_SIZE, np.uint8))
cv2.waitKey(1)
cv2.setMouseCallback(self.window_name, self.on_mouse)
while(not self.done):
canvas = np.zeros(CANVAS_SIZE, np.uint8)
with verrou:
if (len(self.points) > 0):
cv2.polylines(canvas, np.array([self.points]), True, FINAL_LINE_COLOR, 1)
cv2.line(canvas, self.points[-1], self.current, WORKING_LINE_COLOR)
cv2.imshow(self.window_name, canvas)
if cv2.waitKey(50) == 27:
self.done = True
cv2.waitKey()
cv2.destroyWindow(self.window_name)
thread_1 = ZoneDrawer("zone1")
thread_2 = ZoneDrawer("zone2")
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
But this code is still not working. Any help or suggestion ?
The following scrip can be used to select regions of an image using the mouse (as seen in the .gif).
import cv2, numpy as np
# Mouse callback function
global click_list
positions, click_list, shapes = [(0,0)], [], []
def callback(event, x, y, flags, param):
positions[-1] = (x,y)
if event == 1: click_list.append((x,y))
cv2.namedWindow('img')
cv2.setMouseCallback('img', callback)
# Mainloop - show the image and collect the data
while True:
# Create a blank image
img = np.zeros((600,600,3), np.uint8)
# Try to draw the shape being collected
for idx in range(len(click_list)-1):
cv2.line(img, click_list[idx], click_list[idx+1], (0,255,0), 5)
# Draw the stored shapes
for shape in shapes:
for idx in range(len(shape)):
cv2.line(img, shape[idx], shape[idx-1], 255, 5)
# Show the image
cv2.imshow('img', img)
# Wait, and allow the user to quit with the 'esc' key
k = cv2.waitKey(1)
# If user presses 's', go on to the next shape
if k == 115:
shapes.append(click_list)
click_list = []
# If user presses 'esc' break
if k == 27: break
# Clean up
cv2.destroyAllWindows()
I'm newbie in python and i want to learn python. The code(below) is as same as the code i have written in C++. The code works fine in C++ but in python it's not.
My concern is when i hold mouse left button it should draw a circle on image but it's not.
Any help would be appreciated.
code:
import cv2 as cv
import numpy as np
class mouse_state:
def __init__(self):
self.position = [-1,-1]
self.left_button_held = False
self.left_button_clicked = False
def new_iteration():
left_button_clicked = False
def mouse_callback(event, x,y, flag, param):
param = mouse_state()
if event == cv.EVENT_LBUTTONDOWN:
param.position = (x,y)
param.left_button_held = True
print('LMB Down # ', param.position)
elif event == cv.EVENT_LBUTTONUP:
param.position = (x,y)
param.left_button_held = False
param.left_button_clicked = True
print('LMB Up # ', param.position)
elif (flag == cv.EVENT_FLAG_LBUTTON) and (event == cv.EVENT_MOUSEMOVE):
param.position = (x,y)
print('LMB Held, Mouse Moved To',param.position)
cap = cv.VideoCapture(0)
assert cap.isOpened()
windowName = 'Feed'
cv.namedWindow(windowName)
ms = mouse_state()
cv.setMouseCallback(windowName, mouse_callback, ms)
while True:
ret, frame = cap.read()
if not ret: break
(height, width) = frame.shape[:2]
if ms.left_button_clicked or ms.left_button_held:
cv.circle(frame, ms.position, 3, (0,0,255))
cv.circle(frame, ms.position, 10, (255,0,0), 2)
print('Current Position ', ms.position)
ms.new_iteration
cv.imshow(windowName, frame)
w = cv.waitKey(1)
if w == ord('q'):
break
cv.destroyAllWindows()
AM doing a project on selected object tracking as part of it i have to detect orb feature in a selected square region a video using opencv and python.but this code doesn't work.please help me and thanks in advance
import numpy as np
import cv2
rect = (0,0,0,0)
startPoint = False
endPoint = False
def on_mouse(event,x,y,flags,params):
global rect,startPoint,endPoint
# get mouse click
if event == cv2.EVENT_LBUTTONDOWN:
if startPoint == True and endPoint == True:
startPoint = False
endPoint = False
rect = (0, 0, 0, 0)
if startPoint == False:
rect = (x, y, 0, 0)
startPoint = True
elif endPoint == False:
rect = (rect[0], rect[1], x, y)
endPoint = True
cap = cv2.VideoCapture('demo.mp4')
waitTime = 50
#Reading the first frame
(grabbed, frame) = cap.read()
#taking frames one by one
while(cap.isOpened()):
(grabbed, frame) = cap.read()
cv2.namedWindow('frame')
cv2.setMouseCallback('frame', on_mouse)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create()
kp = orb.detect(gray,None)
img2=frame.copy()
frame=cv2.drawKeypoints(gray,kp,img2,color=(0,255,0),flags=0)
cv2.imshow('frame', img2)
#waitkey
if cv2.waitKey(10)==27:
break
cv2.imshow('Video', img2)
cap.release()
cv2.destroyAllWindows()
i am new to opencv -python.
I want to draw a rectangle in a live stream video captured from my webcam. While drawing the rectangle,the video must freeze. I am successful in drawing a rectangle on a image,but i don't know how to do the same on a live video using opencv and python . Please help..
This is a code that I'm using to draw a rectange in videos.
The code works like that:
click on video and the script save the start point
click again and the script save the end point and draw the rectangle
click again to start drawing another retangle
import numpy as np
import cv2
rect = (0,0,0,0)
startPoint = False
endPoint = False
def on_mouse(event,x,y,flags,params):
global rect,startPoint,endPoint
# get mouse click
if event == cv2.EVENT_LBUTTONDOWN:
if startPoint == True and endPoint == True:
startPoint = False
endPoint = False
rect = (0, 0, 0, 0)
if startPoint == False:
rect = (x, y, 0, 0)
startPoint = True
elif endPoint == False:
rect = (rect[0], rect[1], x, y)
endPoint = True
cap = cv2.VideoCapture('../videos/sample.avi')
waitTime = 50
#Reading the first frame
(grabbed, frame) = cap.read()
while(cap.isOpened()):
(grabbed, frame) = cap.read()
cv2.namedWindow('frame')
cv2.setMouseCallback('frame', on_mouse)
#drawing rectangle
if startPoint == True and endPoint == True:
cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 255), 2)
cv2.imshow('frame',frame)
key = cv2.waitKey(waitTime)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()