Python Forum

Full Version: Raspberry Pi camera live feed in tkinter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am new to python not to programming.
I want to display the video feed of my raspberry pi camera in a tkinter frame.
This is my current code but I get an error.
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import tkinter as tk
import numpy as np
from PIL import Image
from PIL import ImageTk
from threading import Thread


canvas = tk.Tk()
canvas.geometry("800x600")
b = tk.Label(canvas)
b.pack() 

def TAKEFOTO():
    camera = PiCamera()
    camera.resolution = (320, 240)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(320, 240))
 
# allow the camera to warmup
    time.sleep(0.1)

# capture frames from the camera
    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
	image = frame.array

	(width,height,other) = image.shape
	

	
	value = image.item(100,100,0)
	for x in range (0,width):
            if(image.item(x,100,0) < 10):
                cv2.rectangle(image,(x,height-100),(0,20),(255,255,255),2)
                break;
        
        
	print(value)
	key = cv2.waitKey(1) & 0xFF
 
	# clear the stream in preparation for the next frame

	image = Image.fromarray(image)
    image = ImageTk.PhotoImage(image)
    b.image = image
	rawCapture.truncate(0)
 
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break



#canvas.pack()

canvas.mainloop()
    
t = Thread (target=TAKEFOTO)
t.start()
The given error is:
28: image = frame.array
SyntaxError: inconsistent use of tabs and spaces in identation

Can somebody please help me?
PS: I am used to programming in c# (may help for explaining)
Hello,
the code under for loop (line #27) is not indented. Be careful though, whether the second for loop is supposed to be inner loop of the first one, or a separate loop.
It is defined, for a strange reason the tab didn't copy.
This is the exact code like it's is in the editor:
https://imgur.com/a/hIfZUwG

Hi,
I replaced all the tabs under the for loop.
Now it runs but there is no live feed getting displayed.
There could be many reasons for live feed not getting displayed, and not necessarily error in the Python code.
Do you get webcam image if you open it with another software used for viewing camera stream?
The light on the camera shows up and if I do cv2.imshow it works. I also get the pixel value that I ask for in the code.
I can't offer an advanced PiCamera user advice. If you got the code elsewhere and it is supposed to work as it is, then you could try to find where the problem happens (e.g. no data arrives) with print statements.
Or, better yet, examine the code line by line, search docs/online for what some function does and if it is used properly in your case.
Where in your code do you update the Label with the image?