【问题标题】:cv2.imshow() function does not show the image if user input is taken, but works otherwisecv2.imshow() 函数在用户输入时不显示图像,否则工作
【发布时间】:2019-10-31 23:37:57
【问题描述】:

我正在编写代码以在 500x500 白色图像上生成用户定义的网格。 程序应要求用户输入网格大小并相应地绘制垂直和水平线并最终显示图像。

我面临的问题是,每当我调用“getGridSize()”函数时,图像都不会显示。但是当我手动为变量“num”赋值时,图像显示会起作用

我也尝试过使用 cv2.waitKey(0) 和 cv2.destroyAllWindows() 但没有成功。

import cv2
import numpy as np

width = 500 # Dimensions of the blank, white image

def main():
##    getGridSize()
    num = 4

    generateWhiteImg()
    lineImg = whiteImg.copy() # Create a copy of the white image to draw upon

    for i in range(0, num):
        spacing = int(width / (num + 1))    # Specify the width between each line, for uniform placement
        point = (i + 1) * spacing   # Change the coordinate of the lines to be drawn by fixed amounts
        lineImg = cv2.line(lineImg, (0, point), (width, point), (0, 0, 0), 3)   # Draw horizontal lines
        lineImg = cv2.line(lineImg, (point, 0), (point, width), (0, 0, 0), 3)   # Draw vertical lines

    cv2.imshow('LINES', lineImg)

## Function to get grid size from user
def getGridSize():
    global num # Stores the size of grid to be drawn
    num = input("Enter the size of blank grid: ")
    num = int(num) # To convert string to integer

## Function to generate a blank, white image
def generateWhiteImg():
    global whiteImg
    img = np.zeros((width, width, 3), np.uint8) # Generate a zeros list, i.e., a black image
    img[:width] = (255, 255, 255) # Convert black image to white
    cv2.imwrite('whiteImg.png', img) # Save the white image
    whiteImg = cv2.imread('whiteImg.png')   # Load the same from directory

if __name__ == "__main__":
    main()

没有错误消息。 我希望代码能按原样工作。我认为问题出在 getGridSize() 函数内部

更新 1:我为此使用 python 3.5.4

【问题讨论】:

    标签: python python-3.x python-2.7 opencv


    【解决方案1】:

    当您使用 OpenCV 进行 GUI 操作时,您总是需要在之后调用 cv2.waitKey() 方法。它确保显示窗口和determines how long the window will stay open

    【讨论】:

    • 我确实使用了“cv2.waitKey(1)”和“cv2.waitKey(0)”,但都没有用。每次我关闭外壳时,图像只会在很短的时间内可见。
    • 如果我也使用“cv2.waitKey(20000)”,它并没有改变任何东西。此外,它应该与“cv2.waitKey(0)”一起工作得很好,对吧?关闭外壳后,图像仅显示一小部分时间。
    • 你把它放在哪里了?我在cv2.imshow('LINES', lineImg) 正下方添加了cv2.waitKey(0),一切正常。请注意,当我使用getGridSize() 时,结果窗口在后台打开。另外,不要使用cv2.waitKey(1),它会打开窗口1毫秒,短时间看。
    • 我的错。它一直在后台打开!嘿,谢谢大家。
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多