1

The regular check for opencv works fine on the buster desktop with

 cv2.imshow('frame',frame)

This code works also fine on ubuntu and mac os

import cv2
import io
import numpy as np
import tornado.httpserver
import tornado.web

from PIL import Image, ImageDraw
from tornado.ioloop import IOLoop

class HandlerCameraIMG(tornado.web.RequestHandler):

    byte_io = io.BytesIO()

    def get(self):
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    jpg = Image.fromarray(img_rgb)
    self.byte_io.seek(0)
    jpg.save(self.byte_io, format="JPEG")
    s = self.byte_io.getvalue()
    self.set_header('Content-type', 'image/jpeg')
    self.set_header('Content-length', len(s))
    self.write(s)
    return

html_index = """<html><body><p>Camera</p>
            <img src="/img/camera.jpeg" style="width:50px;height:50px;"/>
            </body></html>"""

class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
    self.write(html_index)

class WebApplication(tornado.web.Application):
    def __init__(self):
    handlers = [
        (r"/", IndexPageHandler),
        (r'/img/camera.jpeg', HandlerCameraIMG)
    ]
    settings = {'debug': True}
    tornado.web.Application.__init__(self, handlers, **settings)

def main():
    ws_app = WebApplication()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(9090)
    IOLoop.instance().start()

if __name__ == "__main__":
    main()

It does give back a black camera.jpeg on a rapsberry pi 3 with raspian buster

Is there any explainable reason for that ?

user3732793
  • 1,699
  • 4
  • 24
  • 53

1 Answers1

2

There seem to be some problems with indentation in your code, and also an unnecessary dependency on PIL/Pillow and on BytesIO so I removed that and added some error checking and debugging hints and it seems to work fine - maybe you can have another try:

#!/usr/bin/env python3

import cv2
import numpy as np
import tornado.httpserver
import tornado.web

from tornado.ioloop import IOLoop
from tornado.options import define, options

class HandlerCameraIMG(tornado.web.RequestHandler):

    def get(self):
        cap = cv2.VideoCapture(0)
        if (cap.isOpened()== False): 
            print("Error opening video stream or file")

        ret, frame = cap.read()
        if not ret:
            print("Error reading video")
        else:
            print(f"Frame size: {frame.shape}")

        _, JPEG = cv2.imencode('.jpeg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
        self.set_header('Content-type', 'image/jpeg')
        self.set_header('Content-length', len(JPEG))
        self.write(JPEG.tobytes())
        return

html_index = """<html><body><p>Camera</p>
            <img src="/img/camera.jpeg"/>
            </body></html>"""

class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(html_index)

class WebApplication(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexPageHandler),
            (r'/img/camera.jpeg', HandlerCameraIMG)
        ]
        settings = {'debug': True}
        tornado.web.Application.__init__(self, handlers, **settings)

def main():
    define('port', default=6502, help='port to listen on')  
    ws_app = WebApplication()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(options.port)
    print(f'Listening on http://localhost:{options.port}')
    IOLoop.instance().start()

if __name__ == "__main__":
    main()
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • thanks for the example. But as mentioned the code itself runs on other machines without any problem. Also your code shows just a Black Image. – user3732793 Apr 17 '20 at 18:13
  • What size image does it capture from your RasPi camera? – Mark Setchell Apr 17 '20 at 18:27
  • I tested this on a Raspberry Pi and it works fine under Raspbian Buster 10 with Python 3.7 and Tornado 6.0.4. – Mark Setchell Apr 18 '20 at 15:29
  • Maybe try running `raspistill` on your RasPi to check the camera and if that works try `cv2.imwrite('result.jpg', frame)` to see if OpenCV is grabbing the frame correctly. – Mark Setchell Apr 18 '20 at 18:51
  • sorry not to mention I used a usb camera Thought raspistill is only working withe the pi camera. I did not configure any other solution than mentioned in the code above – user3732793 Apr 19 '20 at 13:13
  • So you got no errors printed with my code? What size frame did you capture? – Mark Setchell Apr 19 '20 at 15:05
  • your (and my code) does not set any resolution. And it does work on another machine but not on the pi. not sure what you mean – user3732793 Apr 20 '20 at 08:20
  • My code prints the dimensions of the frame it acquired. Try clicking `Refresh` on your browser a few times. I'm asking what it prints for you. – Mark Setchell Apr 20 '20 at 08:22
  • oh ok sorry didn't notice. It tells Frame size:(480, 640, 3) – user3732793 Apr 20 '20 at 10:39
  • Ok, last check... try saving the image to a file and see if the file is black too. So, after `ret, frame = cap.read()` add a line with `cv2.imwrite('pic.jpg', frame)` – Mark Setchell Apr 20 '20 at 10:46
  • Ok, that means OpenCV can't read your camera correctly and all the Tornado stuff in your question is irrelevant. You need to sort out the basics of video capture with OpenCV first. Have you seen this? https://stackoverflow.com/a/48065148/2836621 – Mark Setchell Apr 20 '20 at 11:17
  • Tahnks for that. It was not there so I added bcm2835-v4l2 to /etcmodules. which did not work. I did also a sudo apt full-upgrade to update it's firmaware. I tried enabling wifi as I read somewhere there the bcm2835 driver is related also to that...still no success. still no success. Technically (with vlc) I can see the camera – user3732793 Apr 20 '20 at 12:24
  • I thin I finally found it. I was able to replicate the problem with fsweb on the command line. I had to skip the first frames to be able to see anything as this is a single capture I never saw something ....it is not a code problem it is a camera problem...thanks for your patience ! – user3732793 Apr 20 '20 at 12:39
  • Cool - glad we got you sorted! Good luck with your project! – Mark Setchell Apr 20 '20 at 13:11