I want to know why you’re making this mistake on the variable?

Asked

Viewed 64 times

0

import numpy as np      # conda install numpy
import cv2 as cv        # conda install opencv
import matplotlib.pyplot as plt
#from PIL import Image  # para rodar no console
def showfig(image, ucmap):
    imgplot=plt.imshow(image, ucmap)

    img = cv.imread("imgs/pfig01.jpg",0)
hf = cv.calcHist([img],[0],None,[256],[0,256])

plt.figure(figsize=(13,5)) 
plt.subplot(121),plt.imshow(img,"gray"),plt.title('Input')
plt.subplot(122),plt.plot(hf),plt.title('Hist')
plt.show()

You’re making this mistake

NameError                                 Traceback (most recent call last)
<ipython-input-15-03db2af2cf65> in <module>()
      7 
      8     img = cv.imread("imgs/pfig01.jpg",0)
----> 9 hf = cv.calcHist([img],[0],None,[256],[0,256])
     10 
     11 plt.figure(figsize=(13,5))

NameError: name 'img' is not defined
  • 1

    Basically because of indentation. You "create" img within the def showfig (create, if called the function). Only try to use it outside the block. This is called "scope" of the variable. It exists only where it was created, in principle.

  • 1

    You have defined the variable img within a function, which by the way is never called. It will not be defined outside of it. In fact, it is quite strange to use commas to separate expressions. What you are doing there is creating tuples that will not be stored. If you only want expressions on the same line, use semicolons.

  • Please read the Bacco comment and confirm to us if the entire code presented should belong to the function or if it should really be out as presented.

1 answer

0

img is a local variable, i.e., it exists only within the function that implements it. It is created when the showfig function is called and ceases to exist when the function is closed. Declare the variable outside the scope of the function so that it can be used globally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.