2015-12-18 95 views
5

我想將13個彩色塊的圖片信息變成一些文本。例如,我需要知道這裏有多少黃色和藍色的塊,以及它們的序列。使用Python在2個組合數組中排列序列

「C:\ target.jpg」

"c:\target.jpg"

「C:\ blue.jpg」

"c:\blue.jpg"

「C:\ yellow.jpg」

"c:\yellow.jpg"

我有什麼是:

import cv2 
import numpy as np 

img_rgb = cv2.imread("c:\\target.jpg") 
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) 
template = cv2.imread('c:\\blue.jpg',0) 
# template = cv2.imread('c:\\blue.jpg',0) 
w, h = template.shape[::-1] 

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) 
threshold = 0.99 
loc = np.where (res >= threshold) 

# if print loc 
# (array([ 3, 31, 59, 87, 115, 143, 171, 199, 227, 255, 283, 311, 339], dtype=int64), array([7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7], dtype=int64)) 


print str(loc[0] + loc[1]) 

當我分開運行,它給出的結果像這樣:

[ 13 41 69 97 125 153 181 209 237 265 293 321 349] 

[ 10 38 66 94 122 150 178 206 234 262 290 318 346] 

那麼這些都是每個13號,但我不知道該怎麼處理它們。

我怎樣才能把它們變成像文本:

「藍,黃,藍,黃,青,藍,黃,黃,藍,黃,藍,黃,藍,黃」。

+0

輸入圖像總是像這樣簡單的固定堆棧,或者他們有時有其他模式,如多列,錯位,旋轉等? –

+0

@John Zwinck,感謝您的評論。塊形狀總是簡單而相同。 –

回答

1

這裏有一個很簡單的解決方案,只是讀取像素向下中心的條紋:

from PIL import Image 
im = Image.open(filename) 

xMin, yMin, xMax, yMax = im.getbbox() 
x = (xMin + xMax)/2 

colors = [] 
oldColor = None 
for y in xrange(yMin, yMax): 
    r, g, b = im.getpixel((x, y)) 

    if r > 240 and g > 240 and b > 240: 
     newColor = 'white' 
    elif g > 150 and b > 150: 
     newColor = 'blue' 
    elif r > 150 and g > 150: 
     newColor = 'yellow' 
    else: 
     newColor = 'unknown' 

    if newColor != oldColor: 
     if newColor != 'white': 
      colors.append(newColor) 
     oldColor = newColor 

print colors 

它打印:

['blue', 'yellow', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'blue', 'yellow', 'blue', 'yellow', 'blue'] 
+0

感謝您的幫助!有用!你的思維方式,讓中間的像素條紋的顏色是一個很好的天使。我將這種方式應用於其他類似的結構圖片,並且它也產生了良好的效果! –

1

有幾種方法可以從這些數字字符串轉換,我會做

bl=[ 13, 41, 69, 97,125,153,181,209,237,265,293,321,349] 
yl=[ 10, 38, 66, 94,122,150,178,206,234,262,290,318,346] 
x=sorted(bl+yl) 
out=', '.join(['blue' if y in bl else 'yellow' for y in x]) 
print out 
+0

感謝您的回答。圖片中有13個顏色塊,但是它顯示了26個輸出,並且它們沒有反映出序列。 –

+0

哦,我明白了,我誤解了這個問題,你能告訴我什麼是'print loc'的輸出。另外,爲什麼你轉換爲灰度?用全綵色工作不是更好嗎? –

+0

@MarkK,我想我發現了你的問題,但是我的OpenCv有問題,現在無法測試,你可以試試這個命令'res = cv2.matchTemplate(img_rgb,template,cv2.TM_CCOEFF_NORMED)'而不是你的matchTemplate,然後'print loc' –