Python 在skimage中裁剪图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33287613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
crop image in skimage?
提问by user824624
I'm using skimage to crop a rectangle in a given image, now I have (x1,y1,x2,y2) as the rectangle coordinates, then I had loaded the image
我正在使用 skimage 在给定的图像中裁剪一个矩形,现在我有 (x1,y1,x2,y2) 作为矩形坐标,然后我已经加载了图像
image = skimage.io.imread(filename)
cropped = image(x1,y1,x2,y2)
However this is the wrong way to crop the image, how would I do it in the right way in skimage
然而,这是裁剪图像的错误方式,我将如何在 skimage 中以正确的方式进行裁剪
回答by Darleison Rodrigues
This seems a simple syntax error.
这似乎是一个简单的语法错误。
Well, in Matlab you can use _'parentheses'_
to extract a pixel or an image region. But in Python, and numpy.ndarray
you should use the brackets to slice a region of your image, besides in this code you is using the wrong way to cut a rectangle.
好吧,在 Matlab 中,您可以_'parentheses'_
用来提取像素或图像区域。但是在 Python 中,numpy.ndarray
您应该使用括号对图像的一个区域进行切片,此外在这段代码中,您使用了错误的方法来切割矩形。
The right way to cut is using the :
operator.
正确的切割方法是使用:
运算符。
Thus,
因此,
from skimage import io
image = io.imread(filename)
cropped = image[x1:x2,y1:y2]
回答by Venkatesan
you can go ahead with the Image module of the PIL library
您可以继续使用 PIL 库的 Image 模块
from PIL import Image
im = Image.open("image.png")
im = im.crop((0, 50, 777, 686))
im.show()
回答by Sandipan Dey
One could use skimage.util.crop()
function too, as shown in the following code:
也可以使用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()
with the following output (with original and cropped image):
具有以下输出(原始图像和裁剪图像):
回答by Gourav Singh Bais
You can crop image using skimage just by slicing the image array like below:
您可以使用 skimage 裁剪图像,只需像下面这样对图像数组进行切片:
image = image_name[y1:y2, x1:x2]
Example Code :
示例代码:
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)