如何用Python选择图像的一部分?
我正在处理卫星图像,我需要从图像中选择一部分进行操作。我该怎么做呢?Im.crop似乎不太管用。那我是不是应该用Resize?
谢谢!
2 个回答
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()
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()
请注意,裁剪区域需要用四个数字来表示,分别是左边、上边、右边和下边。
更多详细信息可以查看这里 使用图像类