Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arranging sequences in 2 combined arrays using Python

Tags:

python

arrays

I am trying to turn information on a picture of 13 colourful blocks into some texts. For example, I need to know how many yellow and blue blocks here, and their sequence.

"c:\target.jpg"

"c:\target.jpg"

"c:\blue.jpg"

"c:\blue.jpg"

"c:\yellow.jpg"

"c:\yellow.jpg"

What I have is:

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])

When I run them separately, it gives results like these:

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

and

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

Well those are each 13 numbers but I don’t know how to handle them.

How can I turn them into texts like:

"blue, yellow, blue, yellow, blue, blue, yellow, yellow, blue, yellow, blue, yellow, blue, yellow".

like image 263
Mark K Avatar asked Oct 30 '22 13:10

Mark K


2 Answers

Here's a quite simple solution that just reads a stripe of pixels down the center:

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

It prints:

['blue', 'yellow', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'blue', 'yellow', 'blue', 'yellow', 'blue']
like image 77
John Zwinck Avatar answered Nov 03 '22 00:11

John Zwinck


There are several ways to convert from those numbers to string, I would do

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
like image 24
Noel Segura Meraz Avatar answered Nov 02 '22 23:11

Noel Segura Meraz