文件被无理复制(Python,OpenCV)

时间:2017-12-12 22:28:56

标签: python opencv

首先,很难解释。如果有人有更好的头衔,请随时编辑/建议。

所以,我正在使用下一个代码从给定的图像中删除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删除了我不希望在最终图片中显示的投资回报率,我会设置一个条件。

这是源文件夹.. src

这是程序发出的输出..

out

正如你所看到的,n°8文件出现为n°7。这是因为程序在该图像中找不到任何可以满足条件的ROI。

问题是我不明白为什么它会复制他工作的最后一个文件(7 ---&gt; 8)。我该如何解决这个问题?

如果没有找到ROI,它应该只复制文件,而不是用最后一个覆盖它。

由于

1 个答案:

答案 0 :(得分:1)

我重写代码,在每次处理之前制作副本,并用颜色填充它们,现在它更清楚了:

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