2

When I am opening a jpg file using cv2.imread() and it fails sometimes which is likely due to BGR format I used. So I switched to PLT to use RGB.

import matplotlib.pyplot as plt
import numpy as np

def rgb_to_gray(img):
        grayImage = np.zeros(img.shape)
        R = np.array(img[:, :, 0])
        G = np.array(img[:, :, 1])
        B = np.array(img[:, :, 2])

        R = (R *.299)
        G = (G *.587)
        B = (B *.114)

        Avg = (R+G+B)
        grayImage = img

        for i in range(3):
           grayImage[:,:,i] = Avg

        return grayImage       

image_file = 'C:\A.jpg';
img = plt.imread(image_file,0)
gray = rgb_to_gray(img).copy()

How ever I am getting an error when I convert the image to gray scale. : "ValueError: assignment destination is read-only" How could I change my code here to avoid it?

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
PCG
  • 2,049
  • 5
  • 24
  • 42

2 Answers2

0

This line appears redundant and causes the error, remove it:

        grayImage = img
Inon Peled
  • 691
  • 4
  • 11
0

Not to sure about the PIL library but if it's based on numpy array try this (https://numpy.org/doc/stable/reference/generated/numpy.copy.html):

grayImage = img.copy()

This will create a fully copy by initializing a whole different instance rather than referencing it (you reference it by using the '=' operator)

https://pythonexamples.org/python-numpy-duplicate-copy-array/#:~:text=Following%20is%20the%20syntax%20to%20make%20a%20copy,of%20array1.%20Example%201%3A%20Copy%20Array%20using%20Numpy

ddwong
  • 27
  • 1
  • 6