如何使用Python选择图像的一部分?

9
我正在处理卫星图像,并需要选择图像的某一部分来进行处理。我该如何做呢?使用Im.crop似乎不起作用。调整大小可以吗?
谢谢。

4
使用 PIL 和 im.crop(box) 通常可以完成工作,详情请参见 http://www.pythonware.com/library/pil/handbook/introduction.htm,您能否发布一些展示您正在做什么的更多代码? - Fredrik Pihl
1
使用GDAL绑定和实用程序。 - Benjamin
2个回答

16
from PIL import Image
im = Image.open("test.jpg")

crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)

cropped_im.show()
注意,裁剪区域必须以4元组的形式给出 - (左,上,右,下)。
更多详细信息请参见使用Image类

我确实这样做了,但是回答是:“'Numpy.ndarray' 对象没有 'crop' 属性。” 这就是我的疑问。 现在该怎么办? - Carlos Pinto da Silva Neto
这意味着您正在尝试将裁剪方法应用于一个Numpy.ndarray实例,但它没有裁剪方法。请确保将裁剪方法应用于PIL的Image类的实例。如果仍然无法使其工作,请发布您的代码。 - symmetry

0

要从大图像中获取较小的图像,只需使用数组索引即可

subImage=Image[ miny:maxy, minx:maxx ]

在这里,您可以在图像上绘制一个矩形,以进行裁剪

import numpy as np
import cv2
import matplotlib.pyplot as plt


def downloadImage(URL):
    """Downloads the image on the URL, and convers to cv2 BGR format"""
    from io import BytesIO
    from PIL import Image as PIL_Image
    import requests

    response = requests.get(URL)
    image = PIL_Image.open(BytesIO(response.content))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)


fig, ax = plt.subplots()

URL = "https://www.godan.info/sites/default/files/old/2015/04/Satellite.jpg"
img = downloadImage(URL)[:, :, ::-1]  # BGR->RGB
plt.imshow(img)

selectedRectangle = None
# Capture mouse-drawing-rectangle event
def line_select_callback(eclick, erelease):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata

    selectedRectangle = plt.Rectangle(
        (min(x1, x2), min(y1, y2)),
        np.abs(x1 - x2),
        np.abs(y1 - y2),
        color="r",
        fill=False,
    )
    ax.add_patch(selectedRectangle)

    imgOnRectangle = img[
        int(min(y1, y2)) : int(max(y1, y2)), int(min(x1, x2)) : int(max(x1, x2))
    ]
    plt.figure()
    plt.imshow(imgOnRectangle)
    plt.show()


from matplotlib.widgets import RectangleSelector

rs = RectangleSelector(
    ax,
    line_select_callback,
    drawtype="box",
    useblit=False,
    button=[1],
    minspanx=5,
    minspany=5,
    spancoords="pixels",
    interactive=True,
)

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接