在skimage中如何裁剪图像?

10

我正在使用skimage裁剪给定图像中的矩形,现在我有(x1,y1,x2,y2)作为矩形坐标,然后已经加载了图像

 image = skimage.io.imread(filename)
 cropped = image(x1,y1,x2,y2)

然而,这种裁剪图像的方法是错误的。我应该如何在skimage中以正确的方式进行裁剪?

4个回答

28

这似乎是一个简单的语法错误。

在Matlab中,你可以使用 '括号' 来提取像素或图像区域。但是在Python和 numpy.ndarray 中,你应该使用方括号来切片图像区域,另外在这段代码中,你使用了错误的方式来裁剪矩形。

正确的裁剪方式是使用 : 运算符。

因此,

from skimage import io
image = io.imread(filename)
cropped = image[x1:x2,y1:y2]

35
在这里使用image[y1:y2, x1:x2]更准确,因为x指的是水平轴。 - iver56

11
可以使用skimage.util.crop()函数,如下所示的代码:
import numpy as np
from skimage.io import imread
from skimage.util import crop
import matplotlib.pylab as plt

A = imread('lena.jpg')

# crop_width{sequence, int}: Number of values to remove from the edges of each axis. 
# ((before_1, after_1), … (before_N, after_N)) specifies unique crop widths at the 
# start and end of each axis. ((before, after),) specifies a fixed start and end 
# crop for every axis. (n,) or n for integer n is a shortcut for before = after = n 
# for all axes.
B = crop(A, ((50, 100), (50, 50), (0,0)), copy=False)

print(A.shape, B.shape)
# (220, 220, 3) (70, 120, 3)

plt.figure(figsize=(20,10))
plt.subplot(121), plt.imshow(A), plt.axis('off') 
plt.subplot(122), plt.imshow(B), plt.axis('off') 
plt.show()

以下是输出结果(包括原始图像和裁剪后的图像):

enter image description here


1
非常赞赏您使用这款经典的老派照片编辑软件! - undefined

2
您可以使用skimage通过对图像数组进行切片来裁剪图像,如下所示:
image = image_name[y1:y2, x1:x2]

示例代码:

from skimage import io
import matplotlib.pyplot as plt

image = io.imread(image_path)
cropped_image = image[y1:y2, x1:x2]
plt.imshow(cropped_image)

0

你可以使用PIL库的Image模块继续进行

from PIL import Image
im = Image.open("image.png")
im = im.crop((0, 50, 777, 686))
im.show()

1
Image not image in from PIL import image - AruniRC
这个问题特别涉及到skimage。 - EzPizza

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