首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python中获取图像中指定区域的所有像素坐标?

如何在python中获取图像中指定区域的所有像素坐标?
EN

Stack Overflow用户
提问于 2018-06-12 16:37:20
回答 1查看 5K关注 0票数 3

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

EN

回答 1

Stack Overflow用户

发布于 2018-06-12 22:46:02

假设是一个矩形,您可以使用np.mgrid为左上角和右下角之间的点生成坐标矩阵。

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

并将它们转换为二维坐标数组。

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

编辑:任意形状

正如Mark Setchell所指出的,你的问题中没有任何关于矩形的内容。

如果要列出任意路径内的所有点,则可以使用matplotlib Path中的contains_points()

下面是一些从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')

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50812749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档