在OpenCV中画线无法工作

3

当我运行这段代码时,本应在黑色表面上画一条直线,但是既没有出现任何错误信息,也没有显示任何内容。出了什么问题?

import numpy as np 
import cv2

class DessinerLigne:
    def dessinerLigne(self):
        # Create a black image
        self.img=np.zeros((512,512,3),np.uint8)

        # Draw a diagonal blue line with thickness of 5 px
        self.img=cv2.line(self.img,(0,0),(511,511),(255,0,0),5)

        # If q is pressed then exit program
        self.k=cv2.waitKey(0)
        if self.k==ord('q'):
            cv2.destroyAllWindows()

if __name__=="__main__":
    DL=DessinerLigne()
    DL.dessinerLigne()

1
你如何在Python中显示图像?我猜在waitKey之前缺少类似于cv2.imshow("windowname", self.img)的代码? - Micka
1
以上的代码仅适用于OpenCV3.0版本,2.4版本无法从cv2.line()返回图像。[并且没有imshow()函数你将看不到任何东西] - berak
@berak,我能在Python 2.7.9中使用OpenCV3.0吗? - user4519127
1个回答

4

OpenCV文档中可以看到,cv2.line()不返回任何内容,但是在原地进行操作。

因此,您的代码可以这样写:

import numpy as np 
import cv2

class DessinerLigne:
    def dessinerLigne(self):
        # Create a black image
        self.img=np.zeros((512,512,3),np.uint8)

        # Draw a diagonal blue line with thickness of 5 px
        cv2.line(self.img,(0,0),(511,511),(255,0,0),5)
        cv2.imshow("Image", self.img)
        # If q is pressed then exit program
        self.k=cv2.waitKey(0)
        if self.k==ord('q'):
            cv2.destroyAllWindows()

if __name__=="__main__":
    DL=DessinerLigne()
    DL.dessinerLigne()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接