Search code examples
pythonnumpyocr

Getting error ValueError: not enough values to unpack (expected 3, got 2)


I am getting this error when I want the gray image to display in vs code, i am unable to fix it.

Error:

 File "d:\OCR_PYTHON\opencv1.py", line 57, in <module>
    display("temp/gray.jpg")
  File "d:\OCR_PYTHON\opencv1.py", line 21, in display     
-->   height, width, depth = im_data.shape
ValueError: not enough values to unpack (expected 3, got 2)

Code:

from turtle import width
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

image_file = "data/image.jpg"


#Display Image

#size will not be good to fit in screen

img = cv.imread(image_file)

#cv.imshow("Original image",img)
#cv.waitKey(0)

#for Best size


def display(im_path):
    
    dpi = 80

    im_data = plt.imread(im_path)

    height, width, depth = im_data.shape

#what size dose the figure need to be in inches to fit the image

    figsize = width/float(dpi), height/float(dpi)

#Creat a figure of the riht size with one ases that takes up the full figure

    fig = plt.figure(figsize=figsize)

    ax = fig.add_axes([0, 0, 1, 1])

#hide the spines,ticks,etc

    ax.axis('off')

#Display the image

    ax.imshow(im_data, cmap='gray')

    plt.show()

#call the display funtion top display

display(image_file)


#Inverted Image

inverted_image=cv.bitwise_not(img)

cv.imwrite("temp/inverted.jpg",inverted_image)

display("temp/inverted.jpg")

#Binarization


def grayscale(image):
    return cv.cvtColor(image, cv.COLOR_BGR2GRAY)


gray_image = grayscale(img)

cv.imwrite("temp/gray.jpg", gray_image)

display("temp/gray.jpg")

Solution

  • You will not receive depth for gray scale images.

    Return Type of matplotlib.pyplot.imread

    The image data. The returned array has shape

    (M, N) for grayscale images.
    (M, N, 3) for RGB images.
    (M, N, 4) for RGBA images.