removing element from ndarray of ndarrys

Viewed 187

I have a 466 x 700 numpy.ndarry. For each ndarray within the 466 x 700 ndarray, I want to delete an element by index. This is what so far:

normalized_img = numpy.atleast_3d(img).astype(numpy.float) / 255.
for x, y in seam:
  numpy.delete(normalized_img[y], x)

seam consists of a coordinate tuple (x, y) and img is a 466 x 700 ndarray with dtype=uint8

I want to delete (x, y) from normalized_img. How do I do so? With pdb.set_trace(), I can see that it is still 466 x 700 even after I've gone iterated through all of seam. seam has a length of 466. I am expecting 466 x 699 after iterating through all of seam.

Example of seam: (13,0), (12,1), (11,2), (10,3), ... etc

I also tried:

normalized_img = numpy.atleast_3d(img).astype(numpy.float) / 255.
for x, y in seam:
  normalized_img[y] = numpy.delete(normalized_img[y], x)

But I get this error:

Traceback (most recent call last):
  File "seam_carver.py", line 118, in <module>
    sys.exit(main(sys.argv))
  File "seam_carver.py", line 114, in main
    sc = SeamCarver(image, int(width), int(height))
  File "seam_carver.py", line 29, in __init__
    self.seam_carve()
  File "seam_carver.py", line 79, in seam_carve
    normalized_img[y] = numpy.delete(normalized_img[y], x)
ValueError: could not broadcast input array from shape (2099) into shape (700,3)

I believe this is due to mismatch of shapes but I am unsure of how to fix this.

1 Answers

I cannot reproduce your problem readily but the documentation states that numpy.delete returns:

A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

Meaning your changes do not apply to the array itself but to its copy, and additional steps are needed to have normalized_img modified.

This assumes that you're going to trim every row by one column (which is what you expect if the final array size is supposed to have one column less?)

tr_sz =(normalized_img.shape[0],normalized_img.shape[1]-1) 
temp = np.zeros(tr_sz)
for x, y in seam:
    temp[y] = np.delete(normalized_img[y], x)

normalized_img = temp
Related