Issue
A big picture (300*300 pixels) divided into 3 areas. 2 small ones (AAA.png and BBB.png) are portions of the big picture.
3-areas.png
AAA.png
BBB.png
I want to know in which areas they located in, i.e. find small pictures in the big picture. The ideal output would be: "AAA.png is in the left"; "BBB.png is in the right".
I have these codes running:
import cv2, os
import numpy as np
big_pic = cv2.imread("c:\\TEM\\3-areas.png")
left_area = big_pic[0:300, 0:100] # [y,y1 : x,x1]
mid_area = big_pic[0:300, 100:200]
right_area = big_pic[0:300, 200:300]
AAA = cv2.imread('C:\\TEM\\AAA.png')
AAA_res = cv2.matchTemplate(left_area,AAA,cv2.TM_CCOEFF_NORMED)
threshold = 0.99
AAA_loc = np.where(AAA_res >= threshold)
a_x_cor = list(AAA_loc[0])
a_y_cor = list(AAA_loc[1])
print a_x_cor, a_y_cor
BBB = cv2.imread('C:\\TEM\\BBB.png')
BBB_res = cv2.matchTemplate(right_area,BBB,cv2.TM_CCOEFF_NORMED)
BBB_loc = np.where(BBB_res >= threshold)
b_x_cor = list(BBB_loc[0])
b_y_cor = list(BBB_loc[1])
print b_x_cor, b_y_cor
I want to simplify it by making for loops. What I tried:
big_pic = cv2.imread("c:\\TEM\\3-areas.png")
list_of_areas = {
left : [0,300, 0,100],
mid : [0,300, 100,200],
right : [0,300, 200,300]}
small_picture_folder = "C:\\TEM\\"
small_pictures = []
root, dirs, files = os.walk(small_picture_folder).next()
for path, subdirs, files in os.walk(root):
for f in files:
if ""AAA"" in f or ""BBB"" in f:
small_pictures.append(small_picture_folder + f)
for key, value in list_of_areas.iteritems():
for y,y1,x,x1 in value:
target_area = big_pic[y:y1, x:x1]
The "for y,y1,x,x1 in value:" line gives error: "TypeError: 'int' object is not iterable."
What would be the best way to achieve it? Thank you.
Solution
In your outer loop, iterating the dictionary entries
for key, value in list_of_areas.iteritems():
the value
is a list of four integers, e.g. [0, 300, 0, 100]
. So, when you now try to iterate this list using
for (...) in value:
you'll get four iterations, and in each iteration, exactly one list item will be "returned" at a time. But now, you try to assign this "returned", single integer value to four variables simultaneously by
for y, y1, x, x1 in value:
hence the error! So, from my point of view, the easiest solution would be, to skip the inner loop, and directly assign all items in value
to your four variables, like so:
for key, value in list_of_areas.iteritems():
y, y1, x, x1 = value
target_area = big_pic[y:y1, x:x1]
Hope that helps!
Answered By - HansHirse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.