-1

I have the following code, which should decrease the width of an image passed as a numpy array by one. Array seam has the column-indices of the pixels to be deleted from corresponding row. To do the deletion, I flatten the matrix, delete the pixels using their coordinates with np.delete (which works for one dimentional arrays only), then try to reshape it back with decremented width, which brings the following error - cannot reshape array of size 832846 into shape (434,639,3)

H, W, C = image.shape
image = image.reshape(H * W, C)
x = np.arange(H)
y = np.array(seam)
indices = x * y + y
image = np.delete(image, indices)
image.reshape(H, W - 1, C)
qkazoo
  • 32
  • 3
  • 2
    434*639*3 = 831978 not 832846. – AboAmmar Jun 05 '22 at 22:24
  • and the specific difference is 868, which is 2x 434 – lemon Jun 05 '22 at 22:25
  • @AboAmmar I know, I want to know where is problem in the code – qkazoo Jun 05 '22 at 22:25
  • The image size after deletions should be divisible by (434 * 3), if it isn't, then you might want to zero-pad the image to be able to reshape. – AboAmmar Jun 05 '22 at 22:34
  • @AboAmmar but if I delete exactly H pixels, (H=434) pixels, and before the deletion it is divisible by 3*434, wouldn't it be divisible after the division as well? – qkazoo Jun 05 '22 at 22:52
  • If you delete H=434 pixels it won't be divisible by 3*434, you have to delete at least 3*434 or pad with zeros as I said. Note that the difference between 434*640*3 and 434*639*3 is exactly 3*434. – AboAmmar Jun 05 '22 at 23:07
  • Does this answer your question? [ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)](https://stackoverflow.com/questions/42947298/valueerror-cannot-reshape-array-of-size-30470400-into-shape-50-1104-104) – Christoph Rackwitz Jun 05 '22 at 23:30
  • please present a [mre]. what is `seam`? your index calculation looks wrong. why not `y*W + x`. what do you notice when you look at the values your variables hold? – Christoph Rackwitz Jun 05 '22 at 23:31

1 Answers1

0

I think there are two mistakes in the code:

(1) to calculate your indices in the flattened array you should multiply x by the column width W, not by y (why?):

indices = x * W + y

(2) to remove a subarray (color pixel in your case) you should indicate the axis to apply the removal to (otherwise you only remove one color component instead of the whole pixel and hence the reshape mismatch):

image = np.delete(image, indices, axis=0)

If I understand what you're trying to achieve, this example should illustrate the idea:

import numpy as np
image = np.arange(45).reshape(5,3,3)
seam = [1, 2, 0, 2, 1]
H, W, C = image.shape
image = image.reshape(H * W, C)
x = np.arange(H)
y = np.array(seam)
indices = x * W + y  # <--- fixed
image = np.delete(image, indices, axis=0)  # <--- fixed
image.reshape(H, W - 1, C)

As a result the pixel at row 0, col 1 will be removed, pixel at row 1 col 2 will be removed etc. Is that right?

isCzech
  • 313
  • 1
  • 1
  • 7