Ask Your Question

reggie's profile - activity

2019-02-24 21:02:34 -0500 received badge  Notable Question (source)
2018-04-06 08:50:36 -0500 received badge  Student (source)
2018-02-06 06:30:53 -0500 received badge  Popular Question (source)
2015-06-04 08:10:35 -0500 asked a question sharing a numpy array between two running python programs on the same computer

I have two opencv2/Python scripts running at the same time on the same computer.

1) a streaming server script, that outputs a live camera feed to the web 2) a motion detection script, that detects movement from a camera

Only one of these scripts can access the camera at once, so I need a way of passing/sharing each frame gathered to the other script.

They both grab the frame from the camera using rc,img = capture.read(); so i'll have to remove that from one of them and somehow pass the img to the other script when rc is true

As the camera frame rate is about 24f/s, I don't think it's feasible to save the img (numpy array) to a file on a disc that they can both access; but I may be wrong!

I've been scratching my head and searching the net for examples on scripts that pass data, but alas i'm stuck.

What would the best approach be to passing a numpy array between two running python programs on the same computer, and could someone kindly provide me some example code?

2015-05-14 06:09:17 -0500 asked a question Measuring light intensity over a percentage of the image

Does opencv2 have a way of measuring light intensity, of a binary image, over a percentage of the image?

I have a movement detector that is working well until the movement crosses a light source; when it wrongly picks up on the adjustments the auto brightness, within the camera, makes.

I thought i could somehow ignore quick and big light intensity changes that occur over say 50% of the image

I'm looking into cv2.calcHist() and np.histogram() but need some expert guidance on a possible approach.

2015-05-12 06:18:06 -0500 received badge  Supporter (source)
2015-05-12 06:18:01 -0500 commented answer re-order my code into a function

I may have misunderstood you, I tried specifying global right after the imports, but that didn't work. Global only seems to make a variable visible from inside to outside a function. I thought specifying a global outside a function made it visible inside all functions, which it clearly doesn't, which I realise now. Thanks :)

2015-05-12 05:44:11 -0500 commented answer re-order my code into a function

I aggree, thanks for that :)

2015-05-12 05:12:06 -0500 commented answer re-order my code into a function

I tried that but it didn't work. Could it be because there are two functions, main() and accu_w()

2015-05-12 05:09:39 -0500 commented answer re-order my code into a function

Would having it inside main() make a difference? If a global is declared inside main() it cannot be seen inside accu_w(). I take your point about keeping away from globals!

2015-05-12 04:56:53 -0500 commented answer re-order my code into a function

Hi Berak,That's what I thought, but this results in 3 windows of live feed, i.e. 3 windows exactly the same as img. I' puzzled as to why. I think its because I don't exactly understand what if avg1 is None: avg1 = np.float32(frame) does.

2015-05-11 06:02:12 -0500 asked a question re-order my code into a function

I'm trying to re order my code and move the commented out lines to the function accu_w(frame). When I do this I get the error:

if avg1 is None: avg1 = np.float32(frame)
UnboundLocalError: local variable 'avg1' referenced before assignment

I'm struggling to understand:

1) What this means?

2) How I can fix it?

The code:

import cv2
import numpy as np

def accu_w(frame):

    if avg1 is None: avg1 = np.float32(frame)
    if avg2 is None: avg2 = np.float32(frame)

    cv2.accumulateWeighted(frame, avg1, 0.05)
    cv2.accumulateWeighted(frame, avg2, 0.0006)

    res1 = cv2.convertScaleAbs(avg1)
    res2 = cv2.convertScaleAbs(avg2)

    cv2.imshow('img',frame)
    cv2.imshow('avg1',res1)
    cv2.imshow('avg2',res2)




def main():

    c = cv2.VideoCapture(0)

    global avg1
    avg1 = None
    global avg2
    avg2 = None

    while(True):


        got_frame,frame = c.read()

        if got_frame:


            accu_w(frame)

            '''
            if avg1 is None: avg1 = np.float32(frame)
            if avg2 is None: avg2 = np.float32(frame)

            cv2.accumulateWeighted(frame, avg1, 0.05)
            cv2.accumulateWeighted(frame, avg2, 0.0006)

            res1 = cv2.convertScaleAbs(avg1)
            res2 = cv2.convertScaleAbs(avg2)

            cv2.imshow('img',frame)
            cv2.imshow('avg1',res1)
            cv2.imshow('avg2',res2)

            '''

            k = cv2.waitKey(20)

            if k == 27:
                break

    cv2.destroyAllWindows()
    c.release()


main()

Iv'e managed to fix it by moving:

if avg1 is None: avg1 = np.float32(frame)
if avg2 is None: avg2 = np.float32(frame)

outside the function, but I still don't understand what the original error meant.

import cv2
import numpy as np



def accu_w(frame):

    cv2.accumulateWeighted(frame, avg1, 0.05)
    cv2.accumulateWeighted(frame, avg2, 0.0006)

    res1 = cv2.convertScaleAbs(avg1)
    res2 = cv2.convertScaleAbs(avg2)

    cv2.imshow('img',frame)
    cv2.imshow('avg1',res1)
    cv2.imshow('avg2',res2)



def main():

    c = cv2.VideoCapture(0)

    global avg1
    avg1 = None
    global avg2
    avg2 = None

    while(True):

        got_frame,frame = c.read()

        if got_frame:


            if avg1 is None: avg1 = np.float32(frame)
            if avg2 is None: avg2 = np.float32(frame)

            accu_w(frame)

            '''        
            cv2.accumulateWeighted(frame, avg1, 0.05)
            cv2.accumulateWeighted(frame, avg2, 0.0006)

            res1 = cv2.convertScaleAbs(avg1)
            res2 = cv2.convertScaleAbs(avg2)


            cv2.imshow('img',frame)
            cv2.imshow('avg1',res1)
            cv2.imshow('avg2',res2)

            '''

            k = cv2.waitKey(20)

            if k == 27:
                break

    cv2.destroyAllWindows()
    c.release()


main()

This appeared to work too, I think its because I have 2 functions and I need to declare the global variables inside each function. I thought if I declare something as global anywhere it could be seen by everything; but one has to declare global variables from within a function for that function to see it from outside.

import cv2
import numpy as np

def accu_w(frame):

    global avg1
    global avg2


    if avg1 is None: avg1 = np.float32(frame)
    if avg2 is None: avg2 = np.float32(frame)

    cv2.accumulateWeighted(frame, avg1, 0.1)
    cv2.accumulateWeighted(frame, avg2, 0.0006)

    res1 = cv2.convertScaleAbs(avg1)
    res2 = cv2.convertScaleAbs(avg2)


    cv2.imshow('img',frame)
    cv2.imshow('avg1',res1)
    cv2.imshow('avg2',res2)




def main():

    c = cv2.VideoCapture(0)


    global avg1
    avg1 = None
    global avg2
    avg2 = None

    while(True ...
(more)
2015-05-11 05:40:43 -0500 answered a question accumulateWeighted code problem

By shifting the avg1=np.float32(f) and avg2=np.float32(f) after the frame has been checked, ie if x==True: and adding if avg(1&2) is None: in front of avg(1&2)=np.float32(f) and lastly adding

avg1 = None 
avg2 = None

has done the trick.

I'm not entirely sure why this has worked, but I think it's to do with letting the camera warm up as berak suggested.

import cv2
import numpy as np

c=cv2.VideoCapture(0) 

avg1 = None
avg2 = None

while(1):

    x,f=c.read()



    if x==True: 

         if avg1 is None: avg1=np.float32(f)
         if avg2 is None: avg2=np.float32(f)   
         #print ("x is true")
         #x,f=c.read()


         cv2.accumulateWeighted(f, avg1, 0.01)
         cv2.accumulateWeighted(f, avg2, 0.1)


         res1=cv2.convertScaleAbs(avg1)
         res2=cv2.convertScaleAbs(avg2)

         cv2.imshow('avg1', res1)
         cv2.imshow('avg2', res2)

         cv2.imshow('f',f)

    k=cv2.waitKey(20)

    if k==27:
        break

cv2.destroyAllWindows()
c.release()
2015-05-03 02:09:25 -0500 commented question streaming http server from inside opencv2 python script?

What a toy, thanks!

2015-05-02 10:20:53 -0500 commented question streaming http server from inside opencv2 python script?

like the above edit?

2015-05-02 09:54:58 -0500 asked a question streaming http server from inside opencv2 python script?

Is it possible to implement a streaming http server whilst working in image processing in opencv2?

eg

#!/usr/bin/env python

    import numpy as np
    import cv2


    runtime_frame_count = 0

    vid = cv2.VideoCapture(0)
    vid.set(3,800)
    vid.set(4,600)

    while True:
        ret, img = vid.read()

        #-----send contents of img to a streaming http server, for access from browser------

        runtime_frame_count = runtime_frame_count + 1
        print (runtime_frame_count)

        # ------ do some other stuff on img in opencv2------------            

        cv2.imshow("input",img)

        key = cv2.waitKey(10)
        key = cv2.waitKey(10)
        key = cv2.waitKey(10)

        if (key == 27) or (runtime_frame_count == 100):
            break

    cv2.destroyAllWindows()

    vid.release()

=================edit===========================================

Following Berak's kind suggestion, Iv'e managed to process an opencv image and serve it to a webpage.

    class CamHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            print (self.path)
            if self.path.endswith('.mjpg'):
                self.send_response(200)
                self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
                self.end_headers()
                while(True):# infinite loop with no exit condition
                        rc,img = capture.read()
                        if not rc:
                            continue 
                        if rc:
                            #========send img to  the cv_frame() function for CV2 operations======
                            imgRGB = cv_frame(img) # contains all the opencv stuff i want to perform
                            #=============================================================

                            #imgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                            r, buf = cv2.imencode(".jpg",imgRGB) 

                            self.wfile.write("--jpgboundary\r\n")
                            self.send_header('Content-type','image/jpeg')
                            self.send_header('Content-length',str(len(buf)))
                            self.end_headers()
                            self.wfile.write(bytearray(buf))
                            self.wfile.write('\r\n')
                            time.sleep(0.01)

                            k = cv2.waitKey(20)
                            if k == 27: 
                                break



                cv2.destroyAllWindows()
                capture.release()   

                return

            if self.path.endswith('.html') or self.path=="/":
                self.send_response(200)
                self.send_header('Content-type','text/html')
                self.end_headers()
                self.wfile.write('<html><head></head><body>')
                self.wfile.write('<img src="http://'+socket.gethostbyname(socket.gethostname())+':'+ str(port) +'/cam.mjpg"/>')
                self.wfile.write('</body></html>')
                return





def main():

    global capture, average
    capture = cv2.VideoCapture(0)

    capture.set(3,800)
    capture.set(4,600)


    while(1):

        server = HTTPServer(('',port),CamHandler)
        print ("server started on: ")
        print(socket.gethostbyname(socket.gethostname()))
        CamHandler.BaseHTTPServer.BaseHTTPRequestHandler("GET", (internalipaddress ,portnumber), CamHandler)
        server.handle_request()
        k = cv2.waitKey(20)

        if k == ord('q'):

            capture.release()
            server.socket.close() 
            print("server stopped")

            cv2.destroyAllWindows()
            break

    return



main()

However, to get the code to run, I have to go to my web browser and request the webpage "localhost:port\" or "localhost:port.html"

Is there a way to call the method "def do_GET()" using python, so the cv_frame(img) function runs all the time?

I cannot work out how to run the function 'cv_frame(img)' all the time, regardless of the server situation.

2015-02-11 08:47:16 -0500 commented question Past ten frame retrieval from a webcam

frame is a numpy array that is pushed into the q. see the below code on how i get the frame.

got_frame, frame = vid.read()
2015-02-11 08:39:53 -0500 commented question Past ten frame retrieval from a webcam

I have made some progress using the class deque (https://docs.python.org/2/library/col...)

from collections import deque
max_qlength = 10
q = deque ([0,max_qlength])

def save_frame_deque(picture, max_qlen):

    max_qlength = max_qlen

    q.append(picture)

    #print(len(q))# actual length of q  
    #print (max_qlength)# max length of q

    if len(q) >  (max_qlength+1): # if actual length of q is bigger than5

        cv2.imshow("frame", q.popleft())
        #or     
        #cv2.imwrite('C:/Users/reg/Desktop/frame_1.png', q.popleft())
        #cv2.imwrite('C:/Users/reg/Desktop/frame_2.png', q.popleft())

call using save_frame_deque(frame,5)

2015-02-09 07:55:16 -0500 asked a question Past ten frame retrieval from a webcam

I have a Python/Opencv2 security camera application that detects movement from a live feed. When a detection is triggered I want to be able to save the last ten frames pria to detection, the detected frames and ten frames following detection as jpgs to a specified folder.

I'm not too sure on how to do this, but would a constantly updating "one in" and "one out" Python frame array be the way to go?

The user could specify to save 10 frames pria, and say 10 frames post detection. Then the frame array would have to constantly store the last 10 frames (frames as a numpy array). Then following detection expand to the detected frames and the user specified post detection number of frames.

Once detection is finished, and the code has added the user specified number of post frames into the array, the array could be emptied, converted to jpgs, and saved to a specified folder.

The array would not be totally emptied, it would always need to contain the pre specified number of frames, just in case of a detection quickly after the first detection.

1) Does this make sense and sound like a valid approach? 2) How can I save a numpy array into a Python array, in effect an array of arrays? 3) Could someone point me towards some opencv2 and python code that does something similar, so I can have a look?

2015-02-01 13:06:40 -0500 commented question accumulateWeighted code problem

My three windows are not black, they show me sat in front of the laptop. When I wave at myself, I'm expecting the different alpha values, currently set to one, to make my moving hand disappear (depending on the differential alpha values I set). I get the same result if I set the alpha values to 0.1 and 0.01. Could it still be a capture problem if I can see three moving video feeds of my ugly mug?

but if I set them to 0.1 and 0.01, to make the forground disapear (depending on the alpha values i set)

2015-01-31 14:58:21 -0500 commented question accumulateWeighted code problem

I took the spaces out of the = and it appears to be working eg a = b to a=b but each screen is the same, and not as expected.

2015-01-31 14:31:26 -0500 edited question accumulateWeighted code problem

The following code is not doing what is expected. If i copy the original code from here it doesnt work at all.

In this state I get three windows from my webcam showing me, but when i wave my hand it doesn't disappear, as expected. I've moved things round to get something working, but I'm stuck now

Any pointers would be welcomed :)

import cv2
import numpy as np

c=cv2.VideoCapture(0) 

while(1):

    x,f=c.read()
    avg1=np.float32(f)
    avg2=np.float32(f)   

    if x==True: 
         #print ("x is true")
         #x,f=c.read()


         cv2.accumulateWeighted(f, avg1, 1)
         cv2.accumulateWeighted(f, avg2, 1)


         res1=cv2.convertScaleAbs(avg1)
         res2=cv2.convertScaleAbs(avg2)

         cv2.imshow('avg1', res1)
         cv2.imshow('avg2', res2)

         cv2.imshow('f',f)

    k=cv2.waitKey(20)

    if k==27:
        break

cv2.destroyAllWindows()
c.release()