pythonpython-3.xnon-type

(Python) TypeError: 'NoneType' object is not subscriptable , in function


I see lots of discusstion fixing 'NoneType error' such as this one Python - TypeError: 'NoneType' object is not subscriptable

but I read about 5 discussion , still don't know how to fix with my case

import numpy as np
import cv2 

def show_img(path):

    img = cv2.imread(path)
    b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
    hist_b = cv2.calcHist([b],[0],None,[256],[0,256])
    hist_g = cv2.calcHist([g],[0],None,[256],[0,256])
    hist_r = cv2.calcHist([r],[0],None,[256],[0,256])
    plt.plot(hist_r, color='r', label="r")
    plt.plot(hist_g, color='g', label="g")
    plt.plot(hist_b, color='b', label="b")
    plt.legend()
    plt.show() 
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = img2[:,:,0], img2[:,:,1], img2[:,:,2]
    hist_h = cv2.calcHist([h],[0],None,[256],[0,256])
    hist_s = cv2.calcHist([s],[0],None,[256],[0,256])
    hist_v = cv2.calcHist([v],[0],None,[256],[0,256])
    plt.plot(hist_h, color='r', label="h")
    plt.plot(hist_s, color='g', label="s")
    plt.plot(hist_v, color='b', label="v")
    plt.legend()
    plt.show()
    
    return hist_r,hist_g, hist_b, hist_h, hist_s, hist_v


aaa = "/home/student_DC/desktop/optimization_11_10/original_duplicate.png "
r,g,b,h,s,v = show_img(aaa)
Traceback (most recent call last):
  File "/home/student_DC/desktop/optimization_11_10/3_color.py", line 31, in <module>
    r,g,b,h,s,v = show_img(aaa)
  File "/home/student_DC/desktop/optimization_11_10/3_color.py", line 7, in show_img
    b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
TypeError: 'NoneType' object is not subscriptable

Solution

  • File system paths can be sensitive to minor naming errors. In your case, there is an extra space at the end of the file name. At the shell level, this would have been stripped out, but the operating system API assumes you really did want that space there.

    Fix, the space, but also consider adding error handling code. After importing sys,

    if img is None:
        print(f"Error in image file '{path}', file=sys.stderr)
        exit(2)
    

    If you got path from the user, you would want to .strip() before use, to avoid minor mistakes.