如何将图片垂直剪成两个大小相等的图片

20
我有一张800 x 600的图像,想使用OpenCV 3.1.0将其垂直切成两个大小相等的图片。这意味着在切割结束时,我应该有两个400 x 600的图片,并分别存储在它们自己的PIL变量中。
以下是示意图: Paper being cut into halves 谢谢。
编辑说明:我想要最有效的解决方案,因此如果使用numpy切片或类似方法的解决方案最为高效,则选择该方案。

7
好图表! - Mark Setchell
3个回答

20
您可以尝试以下代码,它将创建两个numpy.ndarray实例,您可以轻松地显示或写入新文件。
from scipy import misc

# Read the image
img = misc.imread("face.png")
height, width = img.shape

# Cut the image in half
width_cutoff = width // 2
s1 = img[:, :width_cutoff]
s2 = img[:, width_cutoff:]

# Save each half
misc.imsave("face1.png", s1)
misc.imsave("face2.png", s2)

face.png文件是一个示例,需要用您自己的图像文件替换。


1
感谢您的回答。我唯一摆脱的是第三个变量/索引,即height,width,_ = img.shapes1 = img [:,:width_cutoff,:]s2 = img [:,width_cutoff:,:]。由于图像是二维的,程序在我删除这些内容之前一直给出错误提示。 - Elliot Killick
我还尝试使用 width = len(img[0]) 来查找宽度是否更快,但是 numpy 胜出了。Timeit 时间: Numpy Splicing: 0.18052252247208658 len(): 0.2773668664358264 - Elliot Killick
@Halp,你能把这张图片切成两半吗?我想做同样的事情,但是遇到了这个错误。https://pt.stackoverflow.com/questions/343680/erro-ao-dividir-imagem-ao-meio-usando-python - Carlos Diego

4
import cv2   
# Read the image
img = cv2.imread('your file name')
print(img.shape)
height = img.shape[0]
width = img.shape[1]

# Cut the image in half
width_cutoff = width // 2
s1 = img[:, :width_cutoff]
s2 = img[:, width_cutoff:]

cv2.imwrite("file path where to be saved", s1)
cv2.imwrite("file path where to be saved", s2)

2
你可以定义以下函数,将你想要的每个图像简单地切成两个垂直部分。
def imCrop(x):
    height,width,depth = x.shape
    return [x[height , :width//2] , x[height, width//2:]]

然后,您可以通过以下方式简单地绘制图像的右侧:

plt.imshow(imCrop(yourimage)[1])

1
我们如何将此扩展到从文件夹中选择多个图像? - Sanjay

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