Я новичок в обработке изображений и встал на проблему. У меня есть этот образ:Определение цвета внутри контура OpenCV
Моя цель состоит, чтобы превратить его в матрицу с 1, если есть красный внутри клетки и 0, если нет.
Так это будет
10000000000
10001000000
10001000000
10001000000
11111111111
10000000101
10111111101
etc...
Так у меня есть код, где он может извлечь контуры и использует approxPolyDP для определения (х, у) координаты из 4 угловых краев.
Теперь нужно выяснить, как определить, является ли определенный цвет (красный) находится в пределах каждого контура.
Вот некоторые из моего кода: надеюсь, кто-то может помочь!
def extract_cells(grid):
#convert to gray
image_gray = cv2.cvtColor(grid, cv2.COLOR_BGR2GRAY)
#creates a binary image from the gray scale image to use as input for findContours()
#thresh = cv2.adaptiveThreshold(image_gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,11,15)
#Find countors
tempimg, contours, hierarchy = cv2.findContours(image_gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#draw all countours
count = 0
max_size = 0
matrix = []
new_contours = []
grid_contour = 0
grid_contour_row = None
grid_contour_column = None
for each in enumerate(contours):
#used to find the midpoint of each cell
M = cv2.moments(contours[count])
row = int(M['m10']/M['m00'])
column = int(M['m01']/M['m00'])
#find biggest box (this is the grid itself, so needs to be removed since it is not a cell)
size = cv2.contourArea(contours[count])
if (size > max_size):
new_contours.append(contours[grid_contour])
#put a marker in each cell for testing
#if (grid_contour_row != None and grid_contour_column != None):
#cv2.putText(grid, "0", (grid_contour_row, grid_contour_column), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255))
grid_contour = count
grid_contour_row = row
grid_contour_column = column
else:
new_contours.append(contours[count])
#put a marker in each cell for testing
#cv2.putText(grid, "0", (row, column), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255))
#matrix = create_matrix(matrix,count)
count += 1
#draw white lines showing contours
cv2.drawContours(grid, new_contours, -1, (255,255,255))
#approx contains x,y coordinates for the 4 corners of the cell
approx = cv2.approxPolyDP(contours[0],0.01*cv2.arcLength(contours[0],True),True)
cv2.imshow("test", grid)
cv2.waitKey(0)
return new_contours, approx
def identify_colors(image, *colors):
colorlist = []
#Add RGB values for each color specified when the function was called
#to the list colorlist
if "blue" in colors:
colorlist.append(([115,0,0], [255,100,100]))
if "white" in colors:
colorlist.append(([215, 215, 215], [255, 255, 255]))
if "red" in colors:
colorlist.append(([0,0,100], [100,100,255]))
if "green" in colors:
colorlist.append(([0,115,0], [100,255,100]))
#loop over the colorlist
for (lower, upper) in colorlist:
# create NumPy arrays from the colorlist
lower = np.array(lower, dtype = "uint8")
upper = np.array(upper, dtype = "uint8")
#econverts image to b/w with white being anything in the BGR value range
mask = cv2.inRange(image, lower, upper)
#converts that specified range back to its orginal color
output = cv2.bitwise_and(image, image, mask = mask)
#show the photos side by side
#cv2.imshow("images", np.hstack([image, output]))
#cv2.waitKey(0)
return output
Итак, в моем понимании, у вас есть каждый "белый ящик" край координат, верно? Вы можете зацикливаться на каждом белом поле, которое вы нашли, и для каждого окна вы просматриваете исходное изображение (используя координаты окна) для красного пикселя. Если вы его найдете, отметьте его как 1. Вы даже можете использовать координаты белых квадратов для обрезки (копирования) исходного изображения, создав новый Mat - тогда вы можете просто взглянуть на обрезанный Mat для красного пикселя ... –
Это то, о чем я тоже думал. Однако я не уверен, как прокрутить изображение, используя координаты, которые у меня есть. Как вы думаете, вы могли бы привести пример? Извините, я новичок в этом :) – Ashley
Используя краевые координаты небольшого окна, вы должны извлечь субимость/область interes/ROI, просто указав это в матрице изображения. В этом субимаге вы можете искать цвет (используя cv2.inrange). Взгляните на учебное пособие по адресу http://docs.opencv.org/3.1.0/d6/d00/tutorial_py_root.html#gsc.tab=0 – tfv