CaTx
CaTx

Reputation: 1481

How to extract pixels of specified coordinates from image

I am extracting some pixels from an image using the following:

import cv2
import numpy as np
img = cv2.imread('random.png')
targets = np.array([[111, 111], [222, 222], [333, 333]], dtype=np.uint8)
targeted = []
for x, y in targets:
    targeted.append(img[x, y])

Is there a more pythonic or vectorized method to do it in one line instead of this for loop?

Upvotes: 0

Views: 1146

Answers (2)

fountainhead
fountainhead

Reputation: 3722

Perhaps this is what you are looking for (in the place of the for loop):

targeted = img[tuple(targets.T)].tolist()

If you don't want to convert into a list:

targeted = img[tuple(targets.T)]

Upvotes: 1

sam
sam

Reputation: 2311

I got the output after renaming r to targets . It could be because your image object is None. Can you check :

  1. Whether path/image filename is correct
  2. Whether the image has a size of more than 111 (which is the minimum location)(

Upvotes: 0

Related Questions