【问题标题】:How do i make this code to run multiple images in a single folder?如何使此代码在单个文件夹中运行多个图像?
【发布时间】:2019-09-08 10:22:33
【问题描述】:

有人可以帮助修改下面的代码,以便它可以从给定文件夹中循环运行多个图像吗?该代码仅适用于单个图像。 谢谢。

import cv2

img = cv2.imread('6.jpg')

hieght, width = img.shape[:2]

start_row, start_col = int(hieght*0), int(width*0)
end_row, end_col = int(hieght*1), int(width*.5)

cropped = img[start_row: end_row, start_col:end_col]

cv2.imshow('Original', img)
cv2.waitKey(0)

cv2.imshow('Cropped', cropped)
cv2.waitKey(0)

cv2.destroyAllWindows()

【问题讨论】:

标签: python opencv


【解决方案1】:

使用glob

import cv2

import glob
images = glob.glob("D:\\dirtybit\\Pictures\\*")      # get all the images
# print(images)

for img in images:
    img = cv2.imread(img)

    hieght, width = img.shape[:2]

    start_row, start_col = int(hieght*0), int(width*0)
    end_row, end_col = int(hieght*1), int(width*.5)

    cropped = img[start_row: end_row, start_col:end_col]

    cv2.imshow('Original', img)
    cv2.waitKey(0)

    cv2.imshow('Cropped', cropped)
    cv2.waitKey(0)

    cv2.destroyAllWindows()

使用os.listdir(path)

import cv2

import os
images = os.listdir("D:\\dirtybit\\Pictures\\*")

for img in images:
    img = os.path.abspath(img)
    img = cv2.imread(img)

    hieght, width = img.shape[:2]

    start_row, start_col = int(hieght*0), int(width*0)
    end_row, end_col = int(hieght*1), int(width*.5)

    cropped = img[start_row: end_row, start_col:end_col]

    cv2.imshow('Original', img)
    cv2.waitKey(0)

    cv2.imshow('Cropped', cropped)
    cv2.waitKey(0)

    cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2023-02-01
    • 2021-03-06
    • 2017-02-22
    • 2019-03-09
    • 2015-07-28
    相关资源
    最近更新 更多