python-opencv 网络摄像头 [“noneType”]

发布于 2024-09-26 12:51:46 字数 9315 浏览 9 评论 0原文

几周前,我尝试使用 python 和 opencv 移动鼠标指针...我没有时间这样做,今天我意外地发现了一段代码,我的问题是我无法再使用 opencv 打开我的网络摄像头...

我正在使用 ubuntu 10.04 ... /dev/video0 正在工作,我可以执行 luvcview -d /dev/video0

但是当我说camera = highgui.cvCreateCaptureCamera(0) 并尝试输入(camera)时,我得到 noneType ...

我已经 apt-get remove --清除 python-opencv 并重新安装它...但我无法使其工作...不知道出了什么问题几周前它工作了,现在...

这是使用 python opencv 和 Xlib 控制鼠标的代码.. 不知道

#! /usr/bin/env python

print "OpenCV Python version of lkdemo"

import sys
import os

sys.path.insert(1, os.path.join(sys.path[0], '..'))
from Xlib import X, display, Xutil
# import the necessary things for OpenCV
from opencv import cv
from opencv import highgui

#############################################################################
# some "constants"

win_size = 10
MAX_COUNT = 500

#############################################################################
# some "global" variables

image = None
pt = None
add_remove_pt = False
flags = 0
night_mode = False
need_to_init = False

#############################################################################
# the mouse callback

# the callback on the trackbar
class Window:
    def __init__(self, display):
        self.d = display
        self.objects = []

        # Find which screen to open the window on
        self.screen = self.d.screen()

        self.window = self.screen.root.create_window(
            50, 50, 300, 200, 2,
            self.screen.root_depth,
            X.InputOutput,
            X.CopyFromParent,

            # special attribute values
            background_pixel = self.screen.white_pixel,
            event_mask = (X.ExposureMask |
                          X.StructureNotifyMask |
                          X.ButtonPressMask |
                          X.ButtonReleaseMask |
                          X.Button1MotionMask),
            colormap = X.CopyFromParent,
            )

        self.gc = self.window.create_gc(
            foreground = self.screen.black_pixel,
            background = self.screen.white_pixel,
            )
    def mousekiller(self):
        self.gc = self.window.warp_pointer (the_point.x*6, the_point.y*6, src_window = 0, src_x = 0, src_y = 0, src_width = 0, src_height = 0, onerror = None )

        # Set some WM info

        self.WM_DELETE_WINDOW = self.d.intern_atom('WM_DELETE_WINDOW')
        self.WM_PROTOCOLS = self.d.intern_atom('WM_PROTOCOLS')

        self.window.set_wm_name('Xlib example: draw.py')
        self.window.set_wm_icon_name('draw.py')
        self.window.set_wm_class('draw', 'XlibExample')

        self.window.set_wm_protocols([self.WM_DELETE_WINDOW])
        self.window.set_wm_hints(flags = Xutil.StateHint,
                                 initial_state = Xutil.NormalState)

        self.window.set_wm_normal_hints(flags = (Xutil.PPosition | Xutil.PSize
                                                 | Xutil.PMinSize),
                                        min_width = 20,
                                        min_height = 20)

        # Map the window, making it visible
        self.window.map()

def on_mouse (event, x, y, flags, param):

    # we will use the global pt and add_remove_pt
    global pt
    global add_remove_pt

    if image is None:
        return

    if event == highgui.CV_EVENT_LBUTTONDOWN:
        # user has click, so memorize it
        pt = cv.cvPoint (x, y)
        add_remove_pt = True

#############################################################################
# so, here is the main part of the program

if __name__ == '__main__':
    Window(display.Display())
    capture = highgui.cvCreateCameraCapture(-1)           

    # check that capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit (1)

    # display a small howto use it
    print "Hot keys: \n" \
          "\tESC - quit the program\n" \
          "\tr - auto-initialize tracking\n" \
          "\tc - delete all the points\n" \
          "\tn - switch the \"night\" mode on/off\n" \
          "To add/remove a feature point click it\n"

    # first, create the necessary windows

    highgui.cvNamedWindow ('LkDemo', highgui.CV_WINDOW_AUTOSIZE)

    # register the mouse callback
    highgui.cvSetMouseCallback ('LkDemo', on_mouse, None)

    while 1:
        # do forever

        # 1. capture the current image
        frame = highgui.cvQueryFrame (capture)
        if frame is None:
            # no image captured... end the processing
            break

        if image is None:
            # create the images we need
            image = cv.cvCreateImage (cv.cvGetSize (frame), 8, 3)
            image.origin = frame.origin
            grey = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            prev_grey = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            pyramid = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            prev_pyramid = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            points = [[], []]

        # copy the frame, so we can draw on it
        cv.cvCopy (frame, image)

        # create a grey version of the image
        cv.cvCvtColor (image, grey, cv.CV_BGR2GRAY)

        if night_mode:
            # night mode: only display the points
            cv.cvSetZero (image)

        if need_to_init:
            # we want to search all the good points

            # create the wanted images
            eig = cv.cvCreateImage (cv.cvGetSize (grey), 32, 1)
            temp = cv.cvCreateImage (cv.cvGetSize (grey), 32, 1)

            # the default parameters
            quality = 0.01
            min_distance = 10

            # search the good points
            points [1] = cv.cvGoodFeaturesToTrack (
                grey, eig, temp,
                MAX_COUNT,
                quality, min_distance, None, 3, 0, 0.04)

            # refine the corner locations
            cv.cvFindCornerSubPix (
                grey,
                points [1],
                cv.cvSize (win_size, win_size), cv.cvSize (-1, -1),
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS,
                                   20, 0.03))

            # release the temporary images
            cv.cvReleaseImage (eig)
            cv.cvReleaseImage (temp)

        elif len (points [0]) > 0:
            # we have points, so display them

            # calculate the optical flow
            points [1], status = cv.cvCalcOpticalFlowPyrLK (
                prev_grey, grey, prev_pyramid, pyramid,
                points [0], len (points [0]),
                cv.cvSize (win_size, win_size), 3,
                len (points [0]),
                None,
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER|cv.CV_TERMCRIT_EPS,
                                   20, 0.03),
                flags)

            # initializations
            point_counter = -1
            new_points = []

            for the_point in points [1]:
                # go trough all the points

                # increment the counter
                point_counter += 1

                if add_remove_pt:
                    # we have a point to add, so see if it is close to
                    # another one. If yes, don't use it
                    dx = pt.x - the_point.x
                    dy = pt.y - the_point.y
                    if dx * dx + dy * dy <= 25:
                        # too close
                        add_remove_pt = 0
                        continue

                if not status [point_counter]:
                    # we will disable this point
                    continue

                # this point is a correct point
                new_points.append (the_point)

                # draw the current point
                cv.cvCircle (image,
                             [the_point.x, the_point.y],
                             3, cv.cvScalar (0, 255, 0, 0),
                             -1, 8, 0)
                Window(display.Display()).mousekiller()

            # set back the points we keep
            points [1] = new_points

        if add_remove_pt:
            # we want to add a point
            points [1].append (cv.cvPointTo32f (pt))

            # refine the corner locations
            points [1][-1] = cv.cvFindCornerSubPix (
                grey,
                [points [1][-1]],
                cv.cvSize (win_size, win_size), cv.cvSize (-1, -1),
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS,
                                   20, 0.03))[0]

            # we are no more in "add_remove_pt" mode
            add_remove_pt = False

        # swapping
        prev_grey, grey = grey, prev_grey
        prev_pyramid, pyramid = pyramid, prev_pyramid
        points [0], points [1] = points [1], points [0]
        need_to_init = False

        # we can now display the image
        highgui.cvShowImage ('LkDemo', image)

        # handle events
        c = highgui.cvWaitKey (10)

        if c == '\x1b':
            # user has press the ESC key, so exit
            break

        # processing depending on the character
        if c in ['r', 'R']:
            need_to_init = True
        elif c in ['c', 'C']:
            points = [[], []]
        elif c in ['n', 'N']:
            night_mode = not night_mode

该怎么办了...希望有人遇到这个问题并解决... 提前谢谢。

few weeks ago I tryed to move my mouse pointer using python and opencv ...I didnt had time to do it and today I accidentally found a piece of code doing that my problem is that I cant open my webcam anymore with opencv ...

I`m using ubuntu 10.04 ...
/dev/video0 is working I can do luvcview -d /dev/video0

but when I say camera = highgui.cvCreateCaptureCamera(0) and try to type(camera) I get noneType ...

I`ve apt-get remove --purge python-opencv and reinstalled it ...but I cant make it to work ... dont know whats wrong few weeks ago it worked and now ...

here`s the code for controling the mouse with python opencv and Xlib ...

#! /usr/bin/env python

print "OpenCV Python version of lkdemo"

import sys
import os

sys.path.insert(1, os.path.join(sys.path[0], '..'))
from Xlib import X, display, Xutil
# import the necessary things for OpenCV
from opencv import cv
from opencv import highgui

#############################################################################
# some "constants"

win_size = 10
MAX_COUNT = 500

#############################################################################
# some "global" variables

image = None
pt = None
add_remove_pt = False
flags = 0
night_mode = False
need_to_init = False

#############################################################################
# the mouse callback

# the callback on the trackbar
class Window:
    def __init__(self, display):
        self.d = display
        self.objects = []

        # Find which screen to open the window on
        self.screen = self.d.screen()

        self.window = self.screen.root.create_window(
            50, 50, 300, 200, 2,
            self.screen.root_depth,
            X.InputOutput,
            X.CopyFromParent,

            # special attribute values
            background_pixel = self.screen.white_pixel,
            event_mask = (X.ExposureMask |
                          X.StructureNotifyMask |
                          X.ButtonPressMask |
                          X.ButtonReleaseMask |
                          X.Button1MotionMask),
            colormap = X.CopyFromParent,
            )

        self.gc = self.window.create_gc(
            foreground = self.screen.black_pixel,
            background = self.screen.white_pixel,
            )
    def mousekiller(self):
        self.gc = self.window.warp_pointer (the_point.x*6, the_point.y*6, src_window = 0, src_x = 0, src_y = 0, src_width = 0, src_height = 0, onerror = None )

        # Set some WM info

        self.WM_DELETE_WINDOW = self.d.intern_atom('WM_DELETE_WINDOW')
        self.WM_PROTOCOLS = self.d.intern_atom('WM_PROTOCOLS')

        self.window.set_wm_name('Xlib example: draw.py')
        self.window.set_wm_icon_name('draw.py')
        self.window.set_wm_class('draw', 'XlibExample')

        self.window.set_wm_protocols([self.WM_DELETE_WINDOW])
        self.window.set_wm_hints(flags = Xutil.StateHint,
                                 initial_state = Xutil.NormalState)

        self.window.set_wm_normal_hints(flags = (Xutil.PPosition | Xutil.PSize
                                                 | Xutil.PMinSize),
                                        min_width = 20,
                                        min_height = 20)

        # Map the window, making it visible
        self.window.map()

def on_mouse (event, x, y, flags, param):

    # we will use the global pt and add_remove_pt
    global pt
    global add_remove_pt

    if image is None:
        return

    if event == highgui.CV_EVENT_LBUTTONDOWN:
        # user has click, so memorize it
        pt = cv.cvPoint (x, y)
        add_remove_pt = True

#############################################################################
# so, here is the main part of the program

if __name__ == '__main__':
    Window(display.Display())
    capture = highgui.cvCreateCameraCapture(-1)           

    # check that capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit (1)

    # display a small howto use it
    print "Hot keys: \n" \
          "\tESC - quit the program\n" \
          "\tr - auto-initialize tracking\n" \
          "\tc - delete all the points\n" \
          "\tn - switch the \"night\" mode on/off\n" \
          "To add/remove a feature point click it\n"

    # first, create the necessary windows

    highgui.cvNamedWindow ('LkDemo', highgui.CV_WINDOW_AUTOSIZE)

    # register the mouse callback
    highgui.cvSetMouseCallback ('LkDemo', on_mouse, None)

    while 1:
        # do forever

        # 1. capture the current image
        frame = highgui.cvQueryFrame (capture)
        if frame is None:
            # no image captured... end the processing
            break

        if image is None:
            # create the images we need
            image = cv.cvCreateImage (cv.cvGetSize (frame), 8, 3)
            image.origin = frame.origin
            grey = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            prev_grey = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            pyramid = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            prev_pyramid = cv.cvCreateImage (cv.cvGetSize (frame), 8, 1)
            points = [[], []]

        # copy the frame, so we can draw on it
        cv.cvCopy (frame, image)

        # create a grey version of the image
        cv.cvCvtColor (image, grey, cv.CV_BGR2GRAY)

        if night_mode:
            # night mode: only display the points
            cv.cvSetZero (image)

        if need_to_init:
            # we want to search all the good points

            # create the wanted images
            eig = cv.cvCreateImage (cv.cvGetSize (grey), 32, 1)
            temp = cv.cvCreateImage (cv.cvGetSize (grey), 32, 1)

            # the default parameters
            quality = 0.01
            min_distance = 10

            # search the good points
            points [1] = cv.cvGoodFeaturesToTrack (
                grey, eig, temp,
                MAX_COUNT,
                quality, min_distance, None, 3, 0, 0.04)

            # refine the corner locations
            cv.cvFindCornerSubPix (
                grey,
                points [1],
                cv.cvSize (win_size, win_size), cv.cvSize (-1, -1),
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS,
                                   20, 0.03))

            # release the temporary images
            cv.cvReleaseImage (eig)
            cv.cvReleaseImage (temp)

        elif len (points [0]) > 0:
            # we have points, so display them

            # calculate the optical flow
            points [1], status = cv.cvCalcOpticalFlowPyrLK (
                prev_grey, grey, prev_pyramid, pyramid,
                points [0], len (points [0]),
                cv.cvSize (win_size, win_size), 3,
                len (points [0]),
                None,
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER|cv.CV_TERMCRIT_EPS,
                                   20, 0.03),
                flags)

            # initializations
            point_counter = -1
            new_points = []

            for the_point in points [1]:
                # go trough all the points

                # increment the counter
                point_counter += 1

                if add_remove_pt:
                    # we have a point to add, so see if it is close to
                    # another one. If yes, don't use it
                    dx = pt.x - the_point.x
                    dy = pt.y - the_point.y
                    if dx * dx + dy * dy <= 25:
                        # too close
                        add_remove_pt = 0
                        continue

                if not status [point_counter]:
                    # we will disable this point
                    continue

                # this point is a correct point
                new_points.append (the_point)

                # draw the current point
                cv.cvCircle (image,
                             [the_point.x, the_point.y],
                             3, cv.cvScalar (0, 255, 0, 0),
                             -1, 8, 0)
                Window(display.Display()).mousekiller()

            # set back the points we keep
            points [1] = new_points

        if add_remove_pt:
            # we want to add a point
            points [1].append (cv.cvPointTo32f (pt))

            # refine the corner locations
            points [1][-1] = cv.cvFindCornerSubPix (
                grey,
                [points [1][-1]],
                cv.cvSize (win_size, win_size), cv.cvSize (-1, -1),
                cv.cvTermCriteria (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS,
                                   20, 0.03))[0]

            # we are no more in "add_remove_pt" mode
            add_remove_pt = False

        # swapping
        prev_grey, grey = grey, prev_grey
        prev_pyramid, pyramid = pyramid, prev_pyramid
        points [0], points [1] = points [1], points [0]
        need_to_init = False

        # we can now display the image
        highgui.cvShowImage ('LkDemo', image)

        # handle events
        c = highgui.cvWaitKey (10)

        if c == '\x1b':
            # user has press the ESC key, so exit
            break

        # processing depending on the character
        if c in ['r', 'R']:
            need_to_init = True
        elif c in ['c', 'C']:
            points = [[], []]
        elif c in ['n', 'N']:
            night_mode = not night_mode

dont know what to do anymore ... hope someone had this problem and fixed ...
Thx in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想你只要分分秒秒 2024-10-03 12:51:46

如果我理解正确的话,你正在尝试让鼠标反馈发挥作用。

为此,您需要创建一个“响应程序”函数(下面文档中的“OnMouse”函数)。这是由 cv2.setMouseCallBack 函数使用的。

例如:

def mouseHandle(event, x, y, flag, param):
    if (flag == 1):
        print "hoosier at" + str(x) + " , " + str(y);

您还需要在代码中定义标志值,例如:

CV_EVENT_LBUTTONDOWN = 1;

现在在您的主函数中:

im = cv2.imread('myimage.jpg')
cv2.imshow('image', im)
cv2.setMouseCallback('image', mouseHandle, CV_EVENT_LBUTTONDOWN)

作为参考,以下是 opencv 文档中的函数信息:
http://opencv.willowgarage.com/documentation/python/highgui_user_interface.html

SetMouseCallback(windowName, onMouse, param) → 无
为鼠标事件分配回调。

参数:
windowName (str) – 窗口的名称。

onMouse (PyCallableObject) – 每次指定窗口中发生鼠标事件时可调用。该可调用函数应具有签名 Foo(event, x, y, flags, param)-> None 其中 event 是 CV_EVENT_* 之一,x 和 y 是鼠标指针在图像坐标(不是窗口坐标)中的坐标,flags 是 CV_EVENT_FLAG_* 的组合,param 是传递给的用户定义参数调用cvSetMouseCallback函数。

param (object) – 要传递给回调函数的用户定义参数。
函数 cvSetMouseCallback 设置指定窗口内发生的鼠标事件的回调函数。

If I understand correctly you're trying to get mouse feedback to work.

In order to do this, you need to make a "responder" function (the "OnMouse" function in the documentation below). This is used by the cv2.setMouseCallBack function.

For example:

def mouseHandle(event, x, y, flag, param):
    if (flag == 1):
        print "hoosier at" + str(x) + " , " + str(y);

You need to define the flag values in your code as well, for example:

CV_EVENT_LBUTTONDOWN = 1;

Now in your main function:

im = cv2.imread('myimage.jpg')
cv2.imshow('image', im)
cv2.setMouseCallback('image', mouseHandle, CV_EVENT_LBUTTONDOWN)

For reference, here is the function information from the opencv documentation:
http://opencv.willowgarage.com/documentation/python/highgui_user_interface.html

SetMouseCallback(windowName, onMouse, param) → None
Assigns callback for mouse events.

Parameters:
windowName (str) – Name of the window.

onMouse (PyCallableObject) – Callable to be called every time a mouse event occurs in the specified window. This callable should have signature Foo(event, x, y, flags, param)-> None where event is one of CV_EVENT_* , x and y are the coordinates of the mouse pointer in image coordinates (not window coordinates), flags is a combination of CV_EVENT_FLAG_* , and param is a user-defined parameter passed to the cvSetMouseCallback function call.

param (object) – User-defined parameter to be passed to the callback function.
The function cvSetMouseCallback sets the callback function for mouse events occuring within the specified window.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文