Search code examples
pythonimageimage-processingvalueerrorroi

Image analysis with Roipoly. Getting ValueError


I have been trying to use RoiPoly to draw a ROI and find the mean pixel grey value inside a ROI in the image. However, I keep getting the following error:

Traceback (most recent call last):
  File "example.py", line 22, in <module>
    ROI1.displayMean(img)
  File "/home/ruven/Downloads/Rupesh images/roipoly.py", line 74, in displayMean
    mask = self.getMask(currentImage)
  File "/home/ruven/Downloads/Rupesh images/roipoly.py", line 48, in getMask
    ny, nx = np.shape(currentImage)
ValueError: too many values to unpack

This is my code:

import pylab as pl
from roipoly import roipoly 

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# create image
img=mpimg.imread('5.jpg')


# show the image
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
pl.title("left click: line segment         right click: close region")

# let user draw first ROI
ROI1 = roipoly(roicolor='r') #let user draw first ROI

# show the image with the first ROI
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
ROI1.displayROI()
ROI1.displayMean(img)
'''
# show the image with both ROIs and their mean values
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
ROI1.displayMean(img)
pl.title('The ROI')
pl.show()
'''
# show ROI masks
pl.imshow(ROI1.getMask(img),
          interpolation='nearest', cmap="Greys")
pl.title('ROI masks of ROI')
pl.show()

And this is the image:enter image description here

This is the ROI:enter image description here

I am also open to other methods of using an ROI to find the mean pixel grey value


Solution

  • The error you are seeing is due to your input being a 3-channel image (RGB) rather than 1 channel. So when roipoly tries to unpack the shape, it's trying to fit 3 values into 2 variables.

    It should be fixed by converting from a 3-channel image to a 1 channel. Here is one way:

    # create image
    img = mpimg.imread('5.jpg')
    
    print(img.shape)   # (992, 1024, 3)
    img = img[:,:,0]
    print(img.shape)   # (992, 1024)
    

    Or you can read this q/answer for other methods: