(linux) terminate running script - linux

linx terminate running python script , what I know for kill process is that type kill program_ID, but this time I'm not sure how to do, and also don't know the key word to describe or search this problem on web
image in case someone wanna see:
https://ibb.co/xJZ2sQJ
https://ibb.co/Yjgcwwx
I'm inside the command prompt :
(I wrote while loop, so not sure how to stop, I type 'q' also not work)
(venv) joy#raspberrypi:~/Desktop $ python 2.py
^X
:q
q
quit()
quit(q)
kill
.py script
import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Capturing",frame)
# 6.for playing
key = cv2.waitKey(1)
if key == ord('q'):
break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
print(cv2.__version__)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows

Related

Unable to capture image every 5 seconds using OpenCV

I am trying to capture image in every 5 seconds using opencv through my laptop's built-in webcam. I am using time.sleep(5) for the required pause. In every run, the first image seems to be correctly saved but after that rest all the images are being saved as an unsupported format (when i am opening them). Also I am unable to break the loop by pressing 'q'.
Below is my code.
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cap.release()
# Our operations on the frame come here
filename = 'C:/Users/shjohari/Desktop/Retail_AI/MySection/to_predict/image' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Any help is appreciated.
Just a small change, solved my issue.
I included the below code inside the loop :P
cap = cv2.VideoCapture(0)
framerate = cap.get(5)

python cv2 VideoCapture not working on wamp server

Background - I have python and required scripts installed on my desktop.
I am developing a face recognition WebApp.
It is working fine from Command Line but when I try to run it from localhost on wampserver, the webcam lights get on but no webcam window appears and the page starts loading for unlimited time.
Here is the code for data training
#!C:\Users\Gurminders\AppData\Local\Programs\Python\Python35-32\python.exe
import cv2
import os
def assure_path_exists(path):
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.makedirs(dir)
# Start capturing video
vid_cam = cv2.VideoCapture(0)
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, one face id
face_id = input('Please Enter Casual ID --> ')
# Initialize sample face image
count = 0
assure_path_exists("dataset/")
# Start looping
while(True):
# Capture video frame
_, image_frame = vid_cam.read()
# Convert frame to grayscale
gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY)
# Detect frames of different sizes, list of faces rectangles
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# Loops for each faces
for (x,y,w,h) in faces:
# Crop the image frame into rectangle
cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2)
# Increment sample face image
count += 1
# Save the captured image into the datasets folder
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
# Display the video frame, with bounded rectangle on the person's face
cv2.imshow('frame', image_frame)
# To stop taking video, press 'q' for at least 100ms
if cv2.waitKey(100) & 0xFF == ord('q'):
break
# If image taken reach 100, stop taking video
elif count>100:
break
# Stop video
vid_cam.release()
# Close all started windows
cv2.destroyAllWindows()
It works fine on command line but not from localhost on wampserver.
I solved this problem
I replaced
if cv2.waitKey(100) & 0xFF == ord('q'):
With
if cv2.waitKey(5000):
here 5000 are 5 seconds

How to run the python file in Spark

I am having python code in python file.I want to know how to run the python code which is present in one location.I am using Ubuntu OS.In my code, I am getting Json from one URL and need to show as scatter graph using SPARK.I am new to PYSPARK. Please guide me how to achieve this. Please find my below code,
`import multiprocessing
import time
import json
from sseclient import SSEClient as EventSource
# 'Complete your function here i cant understand what you are doing'
# i just placed the code inside check once i dont have the package so u try it
def func(n):
file = open('w.txt','w',encoding='utf8')
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
print(1)
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
json_st=''
stt=''
for event in EventSource(url):
if event.event == 'message':
try:
change = json.loads(event.data)
except ValueError:
pass
else:
print(1)
file.write(str(event.data))
#if file.write(str(event))count <= 10:
#print(event.data)
#print(event.data)
#js=json.loads(event.data)
##print(js['comment'])
#file.write(stt)
#print(stt)
#file.write(str(event))
# count = count + 1
#else:
# break
#print(stt)
#json_str={s}
if __name__ == '__main__':
# Start your process as a process
p = multiprocessing.Process(target=func, name="func", args=(10,))
p.start()
# Wait 3(give your time in secs) seconds for foo
time.sleep(3)
# Terminate func
p.terminate()
# Cleanup
p.join()`
you have to used spark-submit command to running you python script with spark (using command line terminal).
spark-submit /home/sample.py

AttributeError: module 'cv2.cv2' has no attribute 'release'

I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python
import cv2
vid = cv2.VideoCapture(0)
while vid == True:
print("Connected....");
if cv2.waitKey(0) : break
cv2.release();
but i am getting error
AttributeError: module 'cv2.cv2' has no attribute 'release'
while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.
cv2.release() does not exist. I think what you are trying to do is vid.release()
cv2 is the opencv module and vid is the VideoCapture object. which is the one that you have to do the release.
UPDATE:
The code you have has several mistakes. Before I only addressed the one you asked, but lets go through all of them.
First one, the indentation is wrong, I guess maybe it is from copying the code.
Second one
while vid == True:
This is not the correct way to do it. You can use the vid.isOpened() function to see if it opened/connected to the webcam.
Third one, you do not need to use ; after the instructions.
Fourth one, this one is not an error, but something that is not necessary
if cv2.waitKey(0) : break
the if is not necessary, waitKey will return the key pressed as an ascii character, if you use a number other than 0 it will return 0 if no key was pressed. But with 0 it will wait for a key to be pressed "blocking" the current thread (in case you have more than one). However, it will not wait unless that you have a imshow window opened.
Now, the complete code with those changes that I wrote and that checks if the script can connect to a camera will be
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
else:
print ("Not Connected....")
vid.release()
In a similar fashion you can display the video until a key is pressed:
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
while True:
ret, frame = vid.read()
if ret:
cv2.imshow("image", frame)
else:
print ("Error aqcuiring the frame")
break
if cv2.waitKey(10) & 0xFF:
break
else:
print ("Not Connected....")
vid.release()
cv2.destroyAllWindows()
If something is not clear, feel free to ask :)
import cv2
import numpy
img = cv2.imread("lena.jpg", 1)
cv2.imshow("image", img)
cv2.waitKeyEx(0)
cv2.destroyAllWindows()

The Output Window always freezes during uploading or saving files (Open CV on python running on a Raspberry Pi 3)

I made a motion detector solely software-based by referring a few books and then adding my own code. The added code saves a frame of the detected motion locally on the Raspberry Pi and also uploads the same to my Google Drive. Another set of code, sends an email to my email-address informing me of the motion detected.
The problem is that when the file is being saved and uploaded, the Open CV output window freezes until the above processes finish. I tried multiprocessing and multi-threading on python but it didn't help. Is there any way I could improve my logic in a way that it doesn't freeze the output window?
EDIT : The issue was somewhat fixed by removing join() from the two processes. There is a very slight lag but I think that's good enough. Thanks to everyone who replied :)
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
import cv2
from multiprocessing import Process
import numpy as np
import datetime
import time
import smtplib
# make count 0
count = 0
def sf(t2):
cv2.imwrite("/home/pi/Desktop/StoredImages/frame%d.jpg" % count, t2)
# 'google drive authentication' stuff
gauth = GoogleAuth()
# try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# authenticate if not there
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
def upload_file():
file1 = drive.CreateFile({'parent':'/home/pi/Desktop/StoredImages/'})
file1.SetContentFile('/home/pi/Desktop/StoredImages/frame%d.jpg' % count)
file1.Upload()
# 'sending an email' stuff
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login("Removed Intentionally","Removed Intentionally")
msg = "Motion Detected! For more details check your Drive."
# capture Video from the camera module
cap = cv2.VideoCapture(0)
# stores the present date and time
lastUploaded = datetime.datetime.now()
# kernel is created for the dilation process
k = np.ones((3,3),np.uint8) # creates a 3X3 Matrix filled with ones and
# has the data type uint8 (unsigned integer)
# which can contain values from 0 to 255
# first two subsequent frames captured
t0 = cap.read()[1]
t1 = cap.read()[1]
# initially motion detected 0 times
motionCounter = 0
while True:
# difference between two subsequent frames
d=cv2.absdiff(t1,t0)
# stores present date and time
timestamp = datetime.datetime.now()
# converting difference to grayscale
grey = cv2.cvtColor(d,cv2.COLOR_BGR2GRAY)
# grayscale converted to gaussian blur
blur = cv2.GaussianBlur(grey,(3,3),0)
# gaussian blur converted to binary image
ret, th = cv2.threshold(blur, 15, 155, cv2.THRESH_BINARY)
# dilating the image before using the contour function
dilated = cv2.dilate(th,k,iterations=2)
# contour function to find edges
_, contours, heierarchy = cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# copying the original frame to a temporary frame for display
t2 = t0
# drawing green edges around the area with movement
cv2.drawContours(t2, contours, -1, (0,255,0), 2)
# showing output in a new window
cv2.imshow('Output',t2)
# going through each and every contour in the image
for c in contours:
# if contour is lesser than a threshold size, ignore
if cv2.contourArea(c) < 5000:
continue
# if motion occurred after 2 secs
if (timestamp - lastUploaded).seconds >= 2.0:
motionCounter += 1
# if 8 motions occured in 2 secs
if motionCounter >= 8:
# write to a temporary file location using threads
new_process = Process(target=sf, args=(t2,))
new_process.start()
new_process.join()
# upload the temporary pic to Google drive using threads
new_process = Process(target=upload_file)
new_process.start()
new_process.join()
# sending a mail about motion detected
server.sendmail("Removed Intentionally","Removed Intentionally",msg)
# increasing count by 1 and resetting everything
count=count+1
lastUploaded = timestamp
motionCounter = 0
# making the next frame the previous and reading a new frame
t0 = t1
t1 = cap.read()[1]
# esc key breaks the entire loop
if cv2.waitKey(5) == 27:
break
# stops the video stream and exits the window
cap.release()
cv2.destroyAllWindows()
# stops the email server connection
server.quit()
I think you used the multiprocessing in a wrong way. Your code
# write to a temporary file location using threads
new_process = Process(target=sf, args=(t2,))
new_process.start()
new_process.join()
will actually create and start a process, but then it will also wait for it (new_process.join()) to finish. So basically you want to start a parallel running process, but then you wait for it to finish.
Better would be to create and start the processes at the beginning of your program and wait for them to finish at the very end of your program.
Also create a queue for each process (also in the multiprocessing module).
Each process should run in an endless loop and wait for a queue. In your main thread, you feed each process' queue with what it should do (store a file locally, store file remotely)
At the end of your program, you should send your processes a final indication to leave their endless loop, so your new_process.join() statement in the main thread will pick up the fact, that the processes have ended.

Resources