gpt4 book ai didi

python - 文件被无故复制(Python,OpenCV)

转载 作者:行者123 更新时间:2023-12-02 17:38:18 25 4
gpt4 key购买 nike

首先,很难解释。如果某人的标题更好,请随时进行编辑/建议。

因此,我正在使用下一个代码从给定图像中删除ROI。

import cv2
import os
import numpy as np
import shutil

src = (os.path.expanduser('~\\Desktop\\output\\'))

causali = os.listdir(src) # CREO LISTA CAUSALI-2
causali.sort(key=lambda x: int(x.split('.')[0]))

for file in enumerate(causali): # CONTA NUMERO DI FILE CAUSALE

#import image
image = cv2.imread(os.path.expanduser('~\\Desktop\\output\\{}'.format(file[1])))
cv2.imshow('orig',image)
cv2.waitKey(0)

#grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#cv2.imshow('gray',gray)
#cv2.waitKey(0)

#binary
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
#cv2.imshow('second',thresh)
#cv2.waitKey(0)

#dilation
kernel = np.ones((1,80), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
#cv2.imshow('dilated',img_dilation)
#cv2.waitKey(0)

#find contours
im2,ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#sort contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

for i, ctr in enumerate(sorted_ctrs):
# Get bounding box
x, y, w, h = cv2.boundingRect(ctr)

# Getting ROI
roi = image[y:y+h, x:x+w]

if h < 25:
clean = cv2.rectangle(image,(x,y),( x + w, y + h ),(255,255,255),-1)


cv2.imwrite(os.path.expanduser('~\\Desktop\\output2\\{}.png').format(file[0]), clean)

我设置了条件 h < 25来删除我不想在最终图像中可见的ROI。

这是源文件夹。
src

这是程序给出的输出。

out

如您所见,文件8为7。这是因为程序在该图像中找不到适合该条件的任何ROI。

问题是我不明白为什么它会复制他工作的最后一个文件(7 ---> 8)。我怎样才能解决这个问题 ?

如果找不到ROI,则应仅复制文件,而不用最后一个文件覆盖。

谢谢

最佳答案

我重写代码,在每次处理之前进行复制,并用颜色填充它们,现在更加清楚:

import cv2
import os
import numpy as np

causali = os.listdir("causali")
causali.sort(key=lambda x: int(x.split('.')[0]))
print(causali)
for idx, fname in enumerate(causali):
fname = os.path.expanduser("causali/"+fname)
print(fname)
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((1,80), np.uint8)
dilated = cv2.dilate(thresh, kernel, iterations=1)
cnts = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key=lambda cnt: cv2.boundingRect(cnt)[0])

## make an copy first
clean = img.copy()
for i, cnt in enumerate(cnts):
x, y, w, h = cv2.boundingRect(cnt)
roi = img[y:y+h, x:x+w]
if h < 25:
#clean = cv2.rectangle(img,(x,y),( x + w, y + h ),(255,255,255),-1)
clean = cv2.rectangle(img,(x,y),( x + w, y + h ),(0,255,0),-1)

## save the "clean"
cv2.imwrite(os.path.expanduser("output/{}.png").format(idx), clean)

结果如下:
enter image description here

关于python - 文件被无故复制(Python,OpenCV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com