0

ソース画像 (黒い背景と白いオブジェクト) があり、その画像から輪郭を見つけ、黒い背景で新しい空白の画像を作成し、ソース画像にあったようにその画像に輪郭を 1 つずつ描画します。輪郭を見つけて空白の画像を作成する方法は知っていますが、ソース画像と同じように輪郭を描くのに問題があります。いくつかの結果が得られますが、色の塗りつぶしが正しくないか、正しく表示されないことがあります。輪郭の逆を取得して塗りつぶす必要があるかどうかを考えていましたが、それを行う方法やそれが可能かどうかはわかりません。私が基本的にやりたいことは、ビデオに画像の形を1つずつ描画することです。

これが私のコードです。

import cv2
import numpy as np
import sys
import statistics as st


# Function to denoise images
def denoise(contours):
    # Array that contains contours that will be removed
    filtered_cont = []
    sample = []
    # Gathering sample
    for contour in contours:
        sample.append(len(contour))
    # Calculating standard deviation
    stdev = st.stdev(sample)
    for contour in contours:
        # Comparing contour length to standard deviation divided by 3
        if len(contour) < stdev/3:
            # Appending small contours to an array
            filtered_cont.append(contour)
    return filtered_cont

img = cv2.imread(sys.argv[1])

# Getting image dimensions
h,w,l = img.shape
size = (w,h)

gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
contours,hierarchy=cv2.findContours(gray_image,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

noisy_contours = denoise(contours)
# Filtering out noise
cv2.drawContours(img,noisy_contours,-1,color=(0,0,0),thickness=cv2.FILLED)
# Saving denoised image
cv2.imwrite('contours-denoised.png',img)


filtered=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edged=cv2.Canny(filtered,20,100)

# Creating blank black image
blank_image= np.zeros((h, w, 3), np.uint8)

# Finding contours from denoised image
contours,hierarchy=cv2.findContours(edged,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
# Sorting contours from large to small
contours.sort(key=len,reverse=True)

# Initializing video output
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('project.mp4',fourcc, 10, size)

# Iterating through contours
for  cont in contours:
    # Drawing one contour and filling it with white
    cv2.drawContours(blank_image, [cont], -1, color=(255, 255, 255), thickness=cv2.FILLED)
    # Writing image into video stream
    out.write(blank_image)
out.release()

# Saving image
cv2.imwrite('contours-denoised-drawn.png',blank_image)

元の画像 ソース画像

ノイズ除去された元の画像 ソース画像のノイズ除去

キャニーエッジ検出後のノイズ除去画像 キャニーエッジ

ノイズ除去画像の描画バージョン ノイズ除去画像の描画バージョン (Canny 後)

4

0 に答える 0