2017-07-09 26 views
2

私はOpenCVの世界にはまったく新しいものです。私は画像内の数字を検出し、選択して保存する必要があるプロジェクトに取り組んでいます。ROI後のソート画像(Python、OpenCV)

これは私が使用するコードです:

# Importing modules 

import cv2 
import numpy as np 


# Read the input image 
im = cv2.imread('C:\\Users\\User\\Desktop\\test.png') 

# Convert to grayscale and apply Gaussian filtering 
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0) 

# Threshold the image 
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV) 

# Find contours in the image 
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 

# Bounding rectangle for a set of points 
i = 0 

#rects = [cv2.boundingRect(ctr) for ctr in ctrs] 
#rects.sort() 

for ctr in ctrs: 
    x, y, w, h = cv2.boundingRect(ctrs[i]) 

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

    #cv2.imshow('roi',roi) 
    #cv2.waitKey() 

    i += 1 

    cv2.imwrite('C:\\Users\\User\\Desktop\\crop\\' + str(i) + '.jpg', roi) 

#print(rects)  
print("OK - NO ERRORS") 

それは半分に動作します。問題は、出力番号(画像形式では、そのようにする必要があります)が元の画像(以下)で並べられていないことです。

Original test image

これが出力されます。

wrong output

コードで間違っていますか?

また、rectsという変数があります。私はいくつかのデバッグをするためにそれを使用し、面白いことに注意しました。私がコンテンツを並べ替えると、コンソールで画像の並び順が正しいです。

sorted array

元の順序で画像をソートする方法はありますか?

私もこのvery similar postを見ましたが、私は解決策を理解できません。

ありがとうございました。

答えて

1

2次元空間にROIを広げることができれば、自然な順序はありません。

あなたはあなたができる座標xでそれらを注文したい場合は、次の

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

、その後ループsorted_ctrsの代わりctrs超えます。

編集:より正確には:

import cv2 
import numpy as np 

# Read the input image 
im = cv2.imread('JnUpW.png') 

# Convert to grayscale and apply Gaussian filtering 
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0) 

# Threshold the image 
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV) 

# Find contours in the image 
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 

# Sort the bounding boxes 
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 = im[y:y+h, x:x+w] 

    # Write to disk 
    cv2.imwrite(str(i) + '.jpg', roi) 

#print(rects) 
print("OK - NO ERRORS") 
+0

が答えてくれてありがとう。あなたのコードをi = 0カウンタの直後に挿入し、sorted_ctrsを入れましたが、出力は同じです。画像は順調ではありません。 – BlueTrack

+0

それは動作します。どうもありがとうございます。 – BlueTrack

+0

ちょうど、ちょうど分かるのは、この仕分けのプロセスが依存することです。どういう意味ですか?誰が最初に番号5を取って1から始まらないことに決めたのですか? – BlueTrack

関連する問題