Изменить элементы в CvSeq в Python - PullRequest
2 голосов
/ 27 февраля 2011

Я пытаюсь извлечь контуры из изображения, повернуть эти контуры и вставить их в новое изображение. Код приведен ниже. Моя проблема в методе поворота контуров. Когда код выполняется, появляется следующая ошибка: «TypeError: объект« cv.cvseq »не поддерживает назначение элементов».

Есть идеи, как решить эту проблему? Я использую привязки Python для Opencv 2.2.

import cv

def rotateContour(contour, centerOfMass, angle):
    for index in range(0, len(contour)):
        contour[index] = rotatePoint(contour[index], centerOfMass, angle)   
    return contour

def rotatePoint(point, centerOfMass, angle):
    px, py = point
    x, y = centerOfMass
    temppoint = (px-x, py-y)
    temppointx = temppoint[0]*math.cos(angle) + temppoint[1] * math.sin(angle)
    temppointy = temppoint[1]*math.cos(angle) - temppoint[0] * math.sin(angle)
    temppoint = (temppointx + x, temppointy + y)

    return temppoint

inputimage = cv.LoadImage('filename.png', cv.CV_LOAD_IMAGE_GRAYSCALE)
outputimage = cv.CreateImage((10000, 300), 8, 1)

storage = cv.CreateMemStorage (0)
contours = cv.FindContours(inputimage, storage, cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_SIMPLE)

for contour in contour_iterator(contours):
    gray = cv.CV_RGB(200, 200, 200)
    # Rotate contour somehow
    contour = rotatecontour(contour)
    cv.DrawContours(outputimage, contour, gray, gray, 0, -1, 8)

cv.SaveImage("outputfile.png", outputimage)

1 Ответ

1 голос
/ 14 апреля 2011

Кажется, что вы не можете изменить элементы объекта cvseq, используя привязки Python (обратите внимание здесь , что список методов Python для манипулирования объектами cvseq имеет только методы для удаления элементов последовательности и меняя их порядок.)

Тем не менее привязки Python предоставляют инструменты для достижения заявленной цели поворота контуров на изображении.

Поскольку для метода cv.DrawContours() требуется cvseq в качестве входных данных, мы должны найти какой-то другой способ рисования контуров после сохранения и манипулирования ими в Python. Один из способов сделать это - использовать методы cv.FillPoly() или cv.DrawPoly() (которые принимают список списков кортежей в качестве входных данных) в зависимости от того, равен ли параметр толщины, который был бы передан в cv.DrawContours(), -1 или> 0 соответственно. .

Таким образом, один из способов найти контуры и нарисовать их повернутые аналоги будет следующим (где центр масс каждого контура находится путем перерисовки в заполненной форме и использования функций моментов OpenCV):

import cv
import numpy as np

# Draw contour from list of tuples.
def draw_contour( im , contour , color , thickness = 1 , linetype = 8 ,
                  shift = 0 ) :
  if thickness == -1 :
    cv.FillPoly( im , [contour] , color , linetype , shift )
  else :
    cv.PolyLine( im , [contour] , True , color , thickness , linetype , shift )

# Rotate contour around centre point using numpy.
def rotate_contour( contour , centre_point , theta ) :
  rotation = np.array( [ [ np.cos( theta ) , -np.sin( theta ) ] , 
                         [ np.sin( theta ) ,  np.cos( theta ) ] ] )
  centre = np.vstack( [ centre_point ] * len( contour ) )
  contour = np.vstack( contour ) - centre
  contour = np.dot( contour , rotation ) + centre
  return [ tuple ( each_row ) for each_row in contour ]

# Find centre of mass by drawing contour in closed form and using moments.
def find_centre_of_mass( contour ) :
  bottom_right = np.max( contour , axis = 0 )
  blank = cv.CreateImage( tuple ( bottom_right ) , 8 , 1 )
  cv.Set( blank , 0 )
  draw_contour( blank , contour , 1, -1 )
  moments = cv.Moments( blank , 1 )  
  sM00 = float ( cv.GetSpatialMoment( moments , 0 , 0 ) )
  sM01 = float ( cv.GetSpatialMoment( moments , 0 , 1 ) )
  sM10 = float ( cv.GetSpatialMoment( moments , 1 , 0 ) )
  return ( sM10 / sM00 , sM01 / sM00 )

THETA = np.pi / 3.0
COLOR = cv.CV_RGB( 200 , 200 , 200 )
input_image = cv.LoadImage( ‘filename.png’ , cv.CV_LOAD_IMAGE_GRAYSCALE )
output_image = cv.CreateImage( ( input_image.width , input_image.height ) , 
                                 input_image.depth , input_image.nChannels )
cv.Set( output_image , 0 )

storage = cv.CreateMemStorage( 0 )
contour_pointer = cv.FindContours( input_image , storage , 
                                   cv.CV_RETR_EXTERNAL , 
                                   cv.CV_CHAIN_APPROX_SIMPLE )

while contour_pointer is not None :
  contour = contour_pointer [ : ]
  centre_of_mass = find_centre_of_mass( contour )
  rotated_contour = rotate_contour( contour , centre_of_mass , THETA )
  draw_contour( output_image , rotated_contour , COLOR , -1 )
  contour_pointer = contour_pointer.h_next()

cv.SaveImage( ‘outputfile.png’ , output_image)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...