使用Python在2个组合数组中排列序列 [英] Arranging sequences in 2 combined arrays using Python

查看:260
本文介绍了使用Python在2个组合数组中排列序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将13个彩色块的图片上的信息转换为一些文本。例如,我需要知道这里有多少个黄色和蓝色块,以及它们的顺序。

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"

我所拥有的是

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]

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

每个都是13个数字,但我不知道该怎么处理。

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".

推荐答案

这是一个非常简单的解决方案,它仅读取中心下方的像素条:

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

它打印:

['blue', 'yellow', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'blue', 'yellow', 'blue', 'yellow', 'blue']

这篇关于使用Python在2个组合数组中排列序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆