【问题标题】:Iterating through a file of images with os使用 os 遍历图像文件
【发布时间】:2021-05-05 22:44:12
【问题描述】:

我需要遍历一个包含图像的目录。

在每次迭代中,我都需要文件位置和文件名。

我的代码如下,我需要一种方法来循环处理图像文件。

#reads image, converts to HLS, applied Blur
img = cv2.imread("1213.jpg") 
#1213.jpg will need to be replaced with a file location
hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
fin = cv2.GaussianBlur(hls,(25,25),cv2.BORDER_DEFAULT)

#cuts image in half
na = np.array(fin)
orig = na.copy()
m = orig.shape[0]
n = orig.shape[1]/2
M = int(m)
N = int(n)
tiles = [orig[x:x+M,y:y+N] for x in range(0,orig.shape[0]) for y in range(0,orig.shape[1],N)]
variable = tiles[0]

#sets upper and lower boundaries for HLS 
pink_lower = np.array([np.round(  300 / 2), np.round(0.25 * 255), np.round(0.00 * 255)])
pink_upper = np.array([np.round(329 / 2), np.round(5 * 255), np.round(0.30 * 255)])
pink_mask = cv2.inRange(variable, pink_lower, pink_upper)

#crops on image
ys, xs = np.nonzero(pink_mask)
ymin, ymax = ys.min(), ys.max()
xmin, xmax = xs.min(), xs.max()
croped = img[ymin:ymax, xmin:xmax]
croped1 = croped[0:1023,0:255]

cv2.imwrite("processed/croped.png",croped1)
#i need to store my new array as an image with the same name as the original in a new folder
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 查看这个答案:Walking a directory
  • 我还是不明白获取文件名的命令是什么
  • 应该相当容易。您可以在问题中粘贴示例目录结构吗?

标签: python python-3.x numpy file operating-system


【解决方案1】:

给你。提取完整路径和文件名非常简单。

import os

directory = "/path/to/directory"

for filename in os.listdir(directory):
    if filename.endswith(".png") or filename.endswith(".jpg"):
        print(os.path.join(directory, filename))

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2014-04-08
    • 2020-07-27
    • 2021-08-05
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2016-11-26
    • 2017-08-17
    相关资源
    最近更新 更多