2

I will first explain what I want to do. I have an image and I want to store the pixel values for a specific ROI. For that reason I implement the following loop(found in another topic of the site):

pixels = im.load() 

all_pixels = []
for x in range(SpecificWidth):
  for y in range(SpecificHeight):
    cpixel = pixels[x, y]
    all_pixels.append(cpixel)

However, it does not return a SpecificwidthXSpecificHeight matrix but one of length as much as the values. Because I want to keep the size of the matrix of the ROI I implement the following loop(much the same with the previous):

array=np.array(all_pixels)
roi_pixels = np.zeros((SpecificWidth,SpecificHeight))

for i in range(0,array.shape[0],width):
    c_roi_pixels=all_pixels[i]
    roi_pixels.append(c_roi_pixels)

And I have the error as it mentioned in the title.

1
  • To use vstack the arrays should have the same size and I am getting the error: ValueError all the input array dimensions except for the concatenation axis must match exactly. Commented Jul 29, 2014 at 10:28

2 Answers 2

4

In numpy, append is a function, not a method.

So you should use e.g:

roi_pixels = np.append(roi_pixels, c_roi_pixels)

Note that the append function creates and returns a copy! It does not modify the original.

Sign up to request clarification or add additional context in comments.

2 Comments

So the problem is due to the fact that I specify a zero matrix?
No. The problem is that append is not a method of the ndarray class.
2

@RolandSmith is absolutely right about the cause of the error message you're seeing. A much more efficient way to achieve what you're trying to do is to convert the whole image to a numpy array, then use slice indexing to get the pixels corresponding to your ROI:

# convert the image to a numpy array
allpix = np.array(im)

# array of zeros to hold the ROI pixels
roipix = np.zeros_like(allpix)

# copy the ROI region using slice indexing
roipix[:SpecificHeight, :SpecificWidth] = allpix[:SpecificHeight, :SpecificWidth]

3 Comments

The syntax is x[start:stop:step] - you might want to take a look at the documentation here
I erase my comment because I read it before you answer. It works,thanks!
As I said, the syntax is [start:stop:step]. If you want the rows from 0 to 79, and the columns from 0 to 104 (in steps of 1), you could use allpix[0:80:1, 0:105:1]. There are two sets of slice indices in the square brackets, since you're indexing into two dimensions. Also remember that Python indexing starts at 0. Since the default start is 0 and the default step size is 1, you can just specify the stop indices for each dimension, i.e. allpix[:80, :105].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.