Search code examples
pythonopencv

Why does my cv2.imread() giving me None? (python)


I am new to this image detection thing and I've been following a youtube video and trying to make a program that detects an image so I can automate some fishing in a game. BUT I keep getting this error where everytime i made a correct path to the image file i keep getting None output. Could somebody help me with this please?

from numpy import asarray
from mss import mss
import cv2
import time
import pyautogui
import imageio.v3 as iio

import os
import shutil

def vision():
    cords = (400,400,1100,400)
    mark = cv2.imread("D:\\Python\\New folder\\apple.png")

    print(cv2.imshow("OpenCV Image",mark))
    
while True:
    vision()    

My screenshot of the output:

screenshot

expected the image to be read but when i recall it, it wont work.


Solution

  • Did minor edits to your code to make it workable.

    What was happening:

    1. function cv2.imshow(...) doesn't return anything. Thus if you try to wrap it into print you'll see 'None' in the terminal. So the image was processed by cv2, but you only saw None in the outputs. Consider replacing print(cv2.imshow(..)) with cv2.imshow(..).
    2. You were running function vision multiple times in the while loop. This triggered printing None multiple times. Not sure that this is what you wanted to do, I would propose to eliminate this loop.
    3. After calling cv2.imgshow(..) you need to additionally call cv2.waitKey(...), this will make image appear on the screen.
    import cv2
    
    flag_vision = False
    
    def vision():
        cords = (400,400,1100,400)
        mark = cv2.imread("D:\\Python\\New folder\\apple.png")
        cv2.imshow("OpenCV Image",mark)
        cv2.waitKey(0) 
    
    
    
    while True:
       if not flag_vision:
            # prevents function `vision` from running multiple times.
            vision()
            flag_vision = True