本文介绍了如何在python中的图像中指定的区域中获取所有像素坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图像中的区域由4个坐标 x1,y1,x2,y2,x3,y3,x4,y4 定义,我想检索所有像素坐标 x,y 在该区域内.

解决方案

假设为矩形,则可以使用

The area in image is defined by 4 coordinates x1,y1,x2,y2,x3,y3,x4,y4 and I want to retrieve all the pixel coordinates x,y inside that area.

解决方案

Assuming a rectangular shape, you can use np.mgrid to generate a coordinate matrix for the points between your top left and bottom right corners.

X, Y = np.mgrid[xmin:xmax, ymin:ymax]

and convert them to a bidimensional array of coordinates with

np.vstack((X.ravel(), Y.ravel()))


EDIT: arbitrary shapes

As Mark Setchell pointed out, there is nothing in your question that talks about rectangular shapes.

If you want to list all the points inside an arbitrary path, not necessarily of 4 vertices, you can use contains_points() from matplotlib Path.

Here's some code derived from another answer of mine

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path

import skimage.data

# path vertex coordinates
vertices = np.asarray([(100, 100),
                       (300,  80),
                       (350, 200),
                       ( 60, 150)])

# create dummy image
img = skimage.data.chelsea()

# from vertices to a matplotlib path
path = Path(vertices)
xmin, ymin, xmax, ymax = np.asarray(path.get_extents(), dtype=int).ravel()

# create a mesh grid for the whole image, you could also limit the
# grid to the extents above, I'm creating a full grid for the plot below
x, y = np.mgrid[:img.shape[1], :img.shape[0]]
# mesh grid to a list of points
points = np.vstack((x.ravel(), y.ravel())).T

# select points included in the path
mask = path.contains_points(points)
path_points = points[np.where(mask)]

# reshape mask for display
img_mask = mask.reshape(x.shape).T

# now lets plot something to convince ourselves everything works
fig, ax = plt.subplots()

# masked image
ax.imshow(img * img_mask[..., None])
# a random sample from path_points
idx = np.random.choice(np.arange(path_points.shape[0]), 200)
ax.scatter(path_points[idx, 0], path_points[idx, 1], alpha=0.3, color='cyan')

这篇关于如何在python中的图像中指定的区域中获取所有像素坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 21:49