Search code examples
pythonnumpyscikit-image

Image Translation opertaions. ValueError: setting an array element with a sequence


Im learning about digital image processing, but when I perform image translation operations, I get an error message. i get the code from teacher, but somehow it keeps giving me that error message.

Thank you very much!

TypeError: only size-1 arrays can be converted to Python scalars

and

ValueError: setting an array element with a sequence.

My Code :

from skimage import io
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
import numpy as np

url = ("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg")

img = io.imread(url)
img_libgray = rgb2gray(img)
fig, (ax1,ax2) = plt.subplots(1,2)
ax1.imshow(img)
ax2.imshow(img_libgray, cmap=plt.cm.gray)


def translation(img,xtrans,ytrans):
    img_q = np.zeros((img.shape[0]+ytrans,img.shape[1]+xtrans))
    for r in range(0,img.shape[0]):
      for c in range(0,img.shape[1]):
        img_q[r+ytrans,c+xtrans] = img[r,c]
    return img_q

img_tr = translation(img,50,100)
fig, (ax1,ax2) = plt.subplots(1,2)
ax1.imshow(img_libgray, cmap=plt.cm.gray)
ax2.imshow(img_tr, cmap=plt.cm.gray)

The error is below, please someone help me.

TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-9-f480ffd74622> in <module>
      6     return img_q
      7 
----> 8 img_tr = translasi(img,50,100)
      9 fig, (ax1,ax2) = plt.subplots(1,2)
     10 ax1.imshow(img_libgray, cmap=plt.cm.gray)

<ipython-input-9-f480ffd74622> in translasi(img, xtrans, ytrans)
      3     for r in range(0,img.shape[0]):
      4       for c in range(0,img.shape[1]):
----> 5         img_q[r+ytrans,c+xtrans] = img[r,c]
      6     return img_q
      7 

ValueError: setting an array element with a sequence.

Solution

  • I think that img here is probably an RGB or RGBA image, which means it has shape (R, C, 3) or (R, C, 4). So when you write

    img_q = np.zeros((img.shape[0]+ytrans,img.shape[1]+xtrans))
    

    you are creating an image of shape (R', C'), and then when you write:

    img_q[r+ytrans,c+xtrans] = img[r,c]
    

    You are setting a single element/single value (img_q[r+ytrans,c+xtrans]) with a sequence of 3 or 4 values (img[r,c]), because again, img has shape (R, C, 3) or (R, C, 4).

    To fix this problem, I would change the line in which you create img_q:

    img_q = np.zeros(
        (img.shape[0]+ytrans, img.shape[1]+xtrans) + img.shape[2:]
    )