【问题标题】:How to Cut an Image Vertically into Two Equal Sized Images如何将图像垂直切割成两个大小相等的图像
【发布时间】:2018-01-05 04:49:05
【问题描述】:

所以我有一个 800 x 600 的图像,我想使用 OpenCV 3.1.0 将其垂直切割成两张相同大小的图片。这意味着在剪辑结束时,我应该有两个图像,每个图像都是 400 x 600 并且存储在它们自己的 PIL 变量中。

这是一个插图:

谢谢。

编辑:我想要最有效的解决方案,所以如果该解决方案使用 numpy 拼接或类似的东西,那就去吧。

【问题讨论】:

  • 好图!!!

标签: python opencv numpy image-resizing opencv3.1


【解决方案1】:

您可以定义以下函数来简单地将您想要的每个图像切成两个垂直部分。

def imCrop(x):
    height,width,depth = x.shape
    return [x[height , :width//2] , x[height, width//2:]]

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

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

【讨论】:

  • 我们如何将其扩展到文件夹中的多个图像?
【解决方案2】:
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)

【讨论】:

    【解决方案3】:

    您可以尝试以下代码,该代码将创建两个 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 文件是一个示例,需要替换为您自己的图像文件。

    【讨论】:

    • 感谢您的回答。我唯一摆脱的是第三个变量/索引:height, width, _ = img.shapes1 = img[:, :width_cutoff, :]s2 = img[:, width_cutoff:, :] 因为图像是 2D 的,程序给了我一个错误,直到我删除了这些。
    • 我还尝试使用width = len(img[0]) 来查看是否会更快地找到宽度以防万一,但 numpy 占了上风。 Timeit 时间:Numpy 拼接:0.18052252247208658len():0.2773668664358264
    • @Halp 你能把图片切成两半吗?我想做同样的事情,但我有这个错误。 pt.*.com/questions/343680/…