python-casmoothing-0.1/0000775000000000000000000000000012044363170013704 5ustar rootrootpython-casmoothing-0.1/.gitignore0000664000000000000000000000001412044363170015667 0ustar rootroot*.pyc *.swp python-casmoothing-0.1/README.md0000664000000000000000000000033312044363170015162 0ustar rootrootThis is a implementation of the paper "Context-aware mesh smoothing for biomedical applications". It can be used to smooth meshes generated by binary images to remove its staircase artifacts and keep the fine features. python-casmoothing-0.1/HEADER.txt0000755000000000000000000000173312044363170015402 0ustar rootroot#-------------------------------------------------------------------------- # Software: Context Aware Smoothing # Copyright: (C) 2012 Centro de Pesquisas Renato Archer # Homepage: https://github.com/tfmoraes/context_aware_smoothing # Contact: tfmoraes@cti.gov.br # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) #-------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 # da Licenca. # # Este programa eh distribuido na expectativa de ser util, mas SEM # QUALQUER GARANTIA; sem mesmo a garantia implicita de # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. #-------------------------------------------------------------------------- python-casmoothing-0.1/LICENSE-pt.txt0000755000000000000000000004706312044363170016163 0ustar rootrootLICENÇA PÚBLICA GERAL GNU Versão 2, junho de 1991 This is an unofficial translation of the GNU General Public License into Portuguese. It was not published by the Free Software Foundation, and does not legally state the distribution terms for software that uses the GNU GPL -- only the original English text of the GNU GPL does that. However, we hope that this translation will help Portuguese speakers understand the GNU GPL better. Esta é uma tradução não-oficial da Licença Pública Geral GNU ("GPL GNU") para Português. Não foi publicada pela Free Software Foundation, e legalmente não afirma os termos de distribuição de software que utilize a GPL GNU -- apenas o texto original da GPL GNU, em inglês, faz isso. Contudo, esperamos que esta tradução ajude aos que falam português a entender melhor a GPL GNU. Para sugestões ou correcções a esta tradução, contacte: miguel.andrade@neoscopio.com --- Tradução do documento original a partir desta linha --- LICENÇA PÚBLICA GERAL GNU Versão 2, junho de 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA A qualquer pessoa é permitido copiar e distribuir cópias deste documento de licença, desde que sem qualquer alteração. Introdução As licenças de software são normalmente desenvolvidas para restringir a liberdade de compartilhá-lo e modifica-lo. Pelo contrário, a Licença Pública Geral GNU pretende garantir a sua liberdade de compartilhar e modificar o software livre -- garantindo que o software será livre para os seus utilizadores. Esta Licença Pública Geral aplica-se à maioria do software da Free Software Foundation e a qualquer outro programa ao qual o seu autor decida aplicá-la. (Algum software da FSF é cobertos pela Licença Pública Geral de Bibliotecas.) Também poderá aplicá-la aos seus programas. Quando nos referimos a software livre, estamo-nos a referir à liberdade e não ao preço. A Licença Pública Geral (GPL - General Public Licence - em Inglês.) foi desenvolvida para garantir a sua liberdade de distribuir cópias de software livre (e cobrar por isso, se quiser); receber o código-fonte ou ter acesso a ele, se quiser; poder modificar o software ou utilizar partes dele em novos programas livres; e que saiba que está no seu direito de o fazer. Para proteger seus direitos, precisamos fazer restrições que impeçam a qualquer um negar estes direitos ou solicitar que você abdique deles. Estas restrições traduzem-se em certas responsabilidades para si, caso venha a distribuir cópias do software, ou modificá-lo. Por exemplo, se você distribuir cópias de um programa sobre este tipo de licenciamento, gratuitamente ou por alguma quantia, tem que fornecer igualmente todos os direitos que possui sobre ele. Tem igualmente que garantir que os destinatários recebam ou possam obter o código-fonte. Além disto, tem que fornecer-lhes estes termos para que possam conhecer seus direitos. Nós protegemos seus direitos por duas formas que se completam: (1) com copyright do software e (2) com a oferta desta licença, que lhe dá permissão legal para copiar, distribuir e/ou modificar o software. Além disso, tanto para a protecção do autor quanto a nossa, gostaríamos de certificar-nos de que todos entendam que não há qualquer garantia sobre o software livre. Se o software é modificado por alguém e redistribuído, queremos que seus destinatários saibam que o que eles obtiveram não é original, de forma que qualquer problema introduzido por terceiros não interfira na reputação do autor original. Finalmente, qualquer programa é ameaçado constantemente por patentes de software. Queremos evitar o perigo de que distribuidores de software livre obtenham patentes individuais sobre o software, o que teria o efeito de tornar o software proprietário. Para prevenir isso, deixamos claro que qualquer patente tem que ser licenciada para uso livre e gratuito por qualquer pessoa, ou então que nem necessite ser licenciada. Os termos e condições precisas para cópia, distribuição e modificação encontram-se abaixo: LICENÇA PÚBLICA GERAL GNU TERMOS E CONDIÇÕES PARA CÓPIA, DISTRIBUIÇÃO E MODIFICAÇÃO 0. Esta licença aplica-se a qualquer programa ou outro trabalho que contenha um aviso colocado pelo detentor dos direitos autorais informando que aquele pode ser distribuído sob as condições desta Licença Pública Geral. O "Programa" abaixo refere-se a qualquer programa ou trabalho e "trabalho baseado no Programa" significa tanto o Programa em si, como quaisquer trabalhos derivados, de acordo com a lei de direitos de autor: isto quer dizer um trabalho que contenha o Programa ou parte dele, tanto na forma original ou modificado, e/ou tradução para outros idiomas. ***(Doravante o termo "modificação" ou sinónimos serão usados livremente.) *** Cada licenciado é mencionado como "você". Actividades outras que a cópia, a distribuição e modificação não estão cobertas por esta Licença; elas estão fora do seu âmbito. O acto de executar o Programa não é restringido e o resultado do Programa é coberto pela licença apenas se o seu conteúdo contenha trabalhos baseados no Programa (independentemente de terem sido gerados pela execução do Programa). Este último ponto depende das funcionalidades específicas de cada programa. 1. Você pode copiar e distribuir cópias fiéis do código-fonte do Programa da mesma forma que você o recebeu, usando qualquer meio, deste que inclua em cada cópia um aviso de direitos de autor e uma declaração de inexistência de garantias; mantenha intactos todos os avisos que se referem a esta Licença e à ausência total de garantias; e forneça aos destinatários do Programa uma cópia desta Licença, em conjunto com o Programa. Você pode cobrar pelo acto físico de transferir uma cópia e pode, opcionalmente, oferecer garantias em troca de pagamento. 2. Você pode modificar sua cópia ou cópias do Programa, ou qualquer parte dele, gerando assim um trabalho derivado, copiar e distribuir essas modificações ou trabalhos sob os termos da secção 1 acima, desde que se enquadre nas seguintes condições: a) Os arquivos modificados devem conter avisos proeminentes afirmando que você alterou os arquivos, incluindo a data de qualquer alteração. b) Deve ser licenciado, sob os termos desta Licença, integralmente e sem custo algum para terceiros, qualquer trabalho seu que contenha ou seja derivado do Programa ou de parte dele. c) Se qualquer programa modificado, quando executado, lê normalmente comandos interactivamente, tem que fazer com que, quando iniciado o uso interactivo, seja impresso ou mostrado um anúncio de que não há qualquer garantia (ou então que você fornece a garantia) e que os utilizadores podem redistribuir o programa sob estas condições, ainda informando os utilizadores como consultar uma cópia desta Licença. (Excepção: se o Programa em si é interactivo mas normalmente não imprime estes tipos de anúncios, então o seu trabalho derivado não precisa imprimir um anúncio.) Estas exigências aplicam-se ao trabalho derivado como um todo. Se secções identificáveis de tal trabalho não são derivadas do Programa, e podem ser razoavelmente consideradas trabalhos independentes e separados por si só, então esta Licença, e seus termos, não se aplicam a estas secções caso as distribua como um trabalho separado. Mas se distribuir as mesmas secções como parte de um todo que constitui trabalho derivado, a distribuição como um todo tem que enquadrar-se nos termos desta Licença, cujos direitos para outros licenciados se estendem ao todo, portanto também para toda e qualquer parte do programa, independente de quem a escreveu. Desta forma, esta secção não tem a intenção de reclamar direitos ou contestar seus direitos sobre o trabalho escrito completamente por si; ao invés disso, a intenção é a de exercitar o direito de controlar a distribuição de trabalhos, derivados ou colectivos, baseados no Programa. Adicionalmente, a mera adição ao Programa (ou a um trabalho derivado deste) de um outro trabalho num volume de armazenamento ou meio de distribuição não faz esse outro trabalho seja incluído no âmbito desta Licença. 3. Você pode copiar e distribuir o Programa (ou trabalho derivado, conforme descrito na Secção 2) em código-objecto ou em forma executável sob os termos das Secções 1 e 2 acima, desde que cumpra uma das seguintes alienas: a) O faça acompanhar com o código-fonte completo e em forma acessível por máquinas, código esse que tem que ser distribuído sob os termos das Secções 1 e 2 acima e em meio normalmente utilizado para o intercâmbio de software; ou, b) O acompanhe com uma oferta escrita, válida por pelo menos três anos, de fornecer a qualquer um, com um custo não superior ao custo de distribuição física do material, uma cópia do código-fonte completo e em forma acessível por máquinas, código esse que tem que ser distribuído sob os termos das Secções 1 e 2 acima e em meio normalmente utilizado para o intercâmbio de software; ou, c) O acompanhe com a informação que você recebeu em relação à oferta de distribuição do código-fonte correspondente. (Esta alternativa é permitida somente em distribuição não comerciais, e apenas se você recebeu o programa em forma de código-objecto ou executável, com uma oferta de acordo com a Subsecção b) acima.) O código-fonte de um trabalho corresponde à forma de trabalho preferida para se fazer modificações. Para um trabalho em forma executável, o código-fonte completo significa todo o código-fonte de todos os módulos que ele contém, mais quaisquer arquivos de definição de "interface", mais os "scripts" utilizados para se controlar a compilação e a instalação do executável. Contudo, como excepção especial, o código-fonte distribuído não precisa incluir qualquer componente normalmente distribuído (tanto em forma original quanto binária) com os maiores componentes (o compilador, o "kernel" etc.) do sistema operativo sob o qual o executável funciona, a menos que o componente em si acompanhe o executável. Se a distribuição do executável ou código-objecto é feita através da oferta de acesso a cópias em algum lugar, então oferecer o acesso equivalente a cópia, no mesmo lugar, do código-fonte, equivale à distribuição do código-fonte, mesmo que terceiros não sejam compelidos a copiar o código-fonte em conjunto com o código-objecto. 4. Você não pode copiar, modificar, sublicenciar ou distribuir o Programa, excepto de acordo com as condições expressas nesta Licença. Qualquer outra tentativa de cópia, modificação, sublicenciamento ou distribuição do Programa não é valida, e cancelará automaticamente os direitos que lhe foram fornecidos por esta Licença. No entanto, terceiros que receberam de si cópias ou direitos, fornecidos sob os termos desta Licença, não terão a sua licença terminada, desde que permaneçam em total concordância com ela. 5. Você não é obrigado a aceitar esta Licença já que não a assinou. No entanto, nada mais lhe dará permissão para modificar ou distribuir o Programa ou trabalhos derivados deste. Estas acções são proibidas por lei, caso você não aceite esta Licença. Desta forma, ao modificar ou distribuir o Programa (ou qualquer trabalho derivado do Programa), você estará a indicar a sua total concordância com os termos desta Licença, nomeadamente os termos e condições para copiar, distribuir ou modificar o Programa, ou trabalhos baseados nele. 6. Cada vez que redistribuir o Programa (ou qualquer trabalho derivado), os destinatários adquirirão automaticamente do autor original uma licença para copiar, distribuir ou modificar o Programa, sujeitos a estes termos e condições. Você não poderá impor aos destinatários qualquer outra restrição ao exercício dos direitos então adquiridos. Você não é responsável em garantir a concordância de terceiros a esta Licença. 7. Se, em consequência de decisões judiciais ou alegações de violação de patentes ou quaisquer outras razões (não limitadas a assuntos relacionados a patentes), lhe forem impostas condições (por ordem judicial, acordos ou outras formas) e que contradigam as condições desta Licença, elas não o livram das condições desta Licença. Se não puder distribuir de forma a satisfazer simultaneamente suas obrigações para com esta Licença e para com as outras obrigações pertinentes, então como consequência você não poderá distribuir o Programa. Por exemplo, se uma licença de patente não permitir a redistribuição, sem obrigação ao pagamento de "royalties", por todos aqueles que receberem cópias directa ou indirectamente de si, então a única forma de você satisfazer a licença de patente e a esta Licença seria a de desistir completamente de distribuir o Programa. Se qualquer parte desta secção for considerada inválida ou não aplicável em qualquer circunstância particular, o restante da secção aplica-se, e a secção como um todo aplicar-se-á em outras circunstâncias. O propósito desta secção não é o de induzi-lo a infringir quaisquer patentes ou reivindicação de direitos de propriedade de outros, ou a contestar a validade de quaisquer dessas reivindicações; esta secção tem como único propósito proteger a integridade dos sistemas de distribuição de software livre, que é implementado pela prática de licenças públicas. Várias pessoas têm contribuído generosamente e em grande escala para software distribuído usando este sistema, na certeza de que sua aplicação é feita de forma consistente; fica a critério do autor/doador decidir se ele ou ela está disposto(a) a distribuir software utilizando outro sistema, e um outro detentor de uma licença não pode impor esta ou qualquer outra escolha. Esta secção destina-se a tornar bastante claro o que se acredita ser consequência do restante desta Licença. 8. Se a distribuição e/ou uso do Programa são restringidos em certos países por patentes ou direitos de autor, o detentor dos direitos de autor original, que colocou o Programa sob esta Licença, pode incluir uma limitação geográfica de distribuição, excluindo aqueles países, de forma a apenas permitir a distribuição nos países não excluídos. Nestes casos, esta Licença incorpora a limitação como se a mesma constasse escrita nesta Licença. 9. A Free Software Foundation pode publicar versões revistas e/ou novas da Licença Pública Geral de tempos em tempos. Estas novas versões serão similares em espírito à versão actual, mas podem diferir em detalhes que resolvam novos problemas ou situações. A cada versão é dada um número distinto. Se o Programa especifica um número de versão específico desta Licença que se aplica a ele e a "qualquer nova versão", você tem a opção de aceitar os termos e condições daquela versão ou de qualquer outra versão posterior publicada pela Free Software Foundation. Se o programa não especificar um número de versão desta Licença, poderá escolher qualquer versão publicada pela Free Software Foundation. 10. Se você pretende incorporar partes do Programa em outros programas livres cujas condições de distribuição sejam diferentes, escreva ao autor e solicite permissão para tal. Para o software que a Free Software Foundation detém direitos de autor, escreva à Free Software Foundation; às vezes nós permitimos excepções para estes casos. A nossa decisão será guiada por dois objectivos: o de preservar a condição de liberdade de todas os trabalhos derivados do nosso software livre, e o de promover a partilha e reutilização de software de um modo geral. AUSÊNCIA DE GARANTIAS 11. UMA VEZ QUE O PROGRAMA É LICENCIADO SEM ÓNUS, NÃO HÁ QUALQUER GARANTIA PARA O PROGRAMA, NA EXTENSÃO PERMITIDA PELAS LEIS APLICÁVEIS. EXCEPTO QUANDO EXPRESSO DE FORMA ESCRITA, OS DETENTORES DOS DIREITOS AUTORAIS E/OU TERCEIROS DISPONIBILIZAM O PROGRAMA "COMO ESTA", SEM QUALQUER TIPO DE GARANTIAS, EXPRESSAS OU IMPLÍCITAS, INCLUINDO, MAS NÃO LIMITADO A, ÀS GARANTIAS IMPLÍCITAS DE COMERCIALIZAÇÃO E ÀS DE ADEQUAÇÃO A QUALQUER PROPÓSITO. O RISCO COM A QUALIDADE E DESEMPENHO DO PROGRAMA É TOTALMENTE SEU. CASO O PROGRAMA SE REVELE DEFEITUOSO, VOCÊ ASSUME OS CUSTOS DE TODAS AS MANUTENÇÕES, REPAROS E CORRECÇÕES QUE JULGUE NECESSÁRIAS. 12. EM NENHUMA CIRCUNSTÂNCIA, A MENOS QUE EXIGIDO PELAS LEIS APLICÁVEIS OU ACORDO ESCRITO, OS DETENTORES DOS DIREITOS DE AUTOR, OU QUALQUER OUTRA PARTE QUE POSSA MODIFICAR E/OU REDISTRIBUIR O PROGRAMA CONFORME PERMITIDO ACIMA, SERÃO RESPONSABILIZADOS POR SI OU POR SEU INTERMÉDIO, POR DANOS, INCLUINDO QUALQUER DANO EM GERAL, ESPECIAL, ACIDENTAL OU CONSEQUENTE, RESULTANTES DO USO OU INCAPACIDADE DE USO DO PROGRAMA (INCLUINDO, MAS NÃO LIMITADO A, A PERDA DE DADOS OU DADOS TORNADOS INCORRECTOS, OU PERDAS SOFRIDAS POR SI OU POR OUTRAS PARTES, OU FALHAS DO PROGRAMA AO OPERAR COM QUALQUER OUTRO PROGRAMA), MESMO QUE TAIS DETENTORES OU PARTES TENHAM SIDO AVISADOS DA POSSIBILIDADE DE TAIS DANOS. FIM DOS TERMOS E CONDIÇÕES --------------------- Como Aplicar Estes Termos aos Seus Novos Programas Se você desenvolver um novo programa, e quer que ele seja utilizado amplamente pelo público, a melhor forma de alcançar este objectivo é torná-lo software livre, software que qualquer um pode redistribuir e alterar, sob estes termos. Para tal, inclua os seguintes avisos no programa. É mais seguro inclui-los logo no início de cada arquivo-fonte para reforçar mais efectivamente a inexistência de garantias; e cada arquivo deve conter pelo menos a linha de "copyright" e uma indicação sobre onde encontrar o texto completo da licença. Exemplo: Copyright (C) Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo sob os termos da Licença Pública Geral GNU, conforme publicada pela Free Software Foundation; tanto a versão 2 da Licença como (a seu critério) qualquer versão mais actual. Este programa é distribuído na expectativa de ser útil, mas SEM QUALQUER GARANTIA; incluindo as garantias implícitas de COMERCIALIZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM PARTICULAR. Consulte a Licença Pública Geral GNU para obter mais detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU em conjunto com este programa; caso contrário, escreva para a Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. Inclua também informações sobre como contactá-lo electronicamente e por carta. Se o programa é interactivo, faça-o mostrar um aviso breve como este, ao iniciar um modo interactivo: Exemplo: Gnomovision versão 69, Copyright (C) O Gnomovision não possui QUALQUER GARANTIA; para obter mais detalhes escreva `mostrar g'. É software livre e você está convidado a redistribui-lo sob certas condições; digite `mostrar c' para obter detalhes. Os comandos hipotéticos `mostrar g e `mostrar c' devem mostrar as partes apropriadas da Licença Pública Geral. É claro que os comandos que escolher usar podem ser activados de outra forma que `mostrar g' e `mostrar c'; podem ser cliques do rato ou itens de um menu -- o que melhor se adequar ao seu programa. Você também deve obter da sua entidade patronal (se trabalhar como programador) ou escola, conforme o caso, uma "declaração de ausência de direitos autorais" sobre o programa, se necessário. Aqui está um exemplo: Neoscopio Lda., declara a ausência de quaisquer direitos autorais sobre o programa `Gnomovision' escrito por Jorge Andrade. 10 de Junho de 2004 , Miguel Nunes, Gerente de Neoscopio Lda. Esta Licença Pública Geral não permite incorporar o seu programa em programas proprietários. Se o seu programa é uma biblioteca de sub-rotinas, poderá considerar mais útil permitir ligar aplicações proprietárias com a biblioteca. Se é isto que pretende, use a Licença Pública Geral de Bibliotecas GNU, em vez desta Licença. python-casmoothing-0.1/ca_smoothing.cxx0000664000000000000000000002375212044363170017113 0ustar rootroot//-------------------------------------------------------------------------- // Software: Context Aware Smoothing // Copyright: (C) 2012 Centro de Tecnologia da Informação Renato Archer // Homepage: https://github.com/tfmoraes/context_aware_smoothing // Contact: tfmoraes@cti.gov.br // License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) //-------------------------------------------------------------------------- // Este programa e software livre; voce pode redistribui-lo e/ou // modifica-lo sob os termos da Licenca Publica Geral GNU, conforme // publicada pela Free Software Foundation; de acordo com a versao 2 // da Licenca. // // Este programa eh distribuido na expectativa de ser util, mas SEM // QUALQUER GARANTIA; sem mesmo a garantia implicita de // COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM // PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais // detalhes. //-------------------------------------------------------------------------- #include "ca_smoothing.h" vtkPolyData* ca_smoothing(vtkPolyData* pd, double T, double tmax, double bmin, int n_iter) { const double stack_orientation[3] = { 0, 0, 1 }; vtkPolyData *tpd; vtkIdList *vertices_staircase; vtkDoubleArray* weights; printf("Finding staircase artifacts\n"); printf("Number of points %lld\n", pd->GetNumberOfPoints()); vertices_staircase = find_staircase_artifacts(pd, stack_orientation, T); printf("Calculating the Weights\n"); weights = calc_artifacts_weight(pd, vertices_staircase, tmax, bmin); printf("Taubin Smooth\n"); tpd = taubin_smooth(pd, weights, 0.5, -0.53, n_iter); vertices_staircase->Delete(); weights->Delete(); return tpd; } vtkIdList* find_staircase_artifacts(vtkPolyData* pd, const double stack_orientation[3], double T) { /* This function is used to find vertices at staircase artifacts, which are those vertices whose incident faces' orientation differences are aproximated 90°. The argument `pd' is a vtkPolydata, it have to be its faces orientation (normal) calculated before and make sure that BuildLinks() has been called. */ int nv, nf, fid; double of_z, of_y, of_x, min_z, max_z, min_y, max_y, min_x, max_x; double *ni; vtkIdList *output = vtkIdList::New(); vtkIdList *idfaces = vtkIdList::New();//idfaces = vtk.vtkIdList() nv = pd->GetNumberOfPoints(); // Number of vertices. for (int vid=0; vid < nv; vid++){ //for vid in xrange(nv): pd->GetPointCells(vid, idfaces); //pd.GetPointCells(vid, idfaces) # Getting faces connected to face vid. nf = idfaces->GetNumberOfIds(); max_z = -1000; min_z = 1000; max_y = -1000; min_y = 1000; max_x = -1000; min_x = 1000; for (int nid=0; nid < nf; nid++) { fid = idfaces->GetId(nid); ni = pd->GetCellData()->GetArray("Normals")->GetTuple(fid); of_z = 1 - abs(ni[0]*stack_orientation[0] + ni[1]*stack_orientation[1] + ni[2]*stack_orientation[2]); of_y = 1 - abs(ni[0]*0 + ni[1]*1 + ni[2]*0); of_x = 1 - abs(ni[0]*1 + ni[1]*0 + ni[2]*0); if (of_z > max_z) max_z = of_z; if (of_z < min_z) min_z = of_z; if (of_y > max_y) max_y = of_y; if (of_y < min_y) min_y = of_y; if (of_x > max_x) max_x = of_x; if (of_x < min_x) min_x = of_x; // Getting the ones which normals dot is 90°, its vertex is added to // output if ((abs(max_z - min_z) >= T) || (abs(max_y - min_y) >= T) || (abs(max_x - min_x) >= T)) { output->InsertNextId(vid); break; } } idfaces->Reset(); } return output; } vtkIdList* get_near_vertices_to_v(vtkPolyData* pd, int v, double dmax){ /* Returns all vertices with distance at most "d" to the vertice "v" with their distances. pd - vtkPolydata v - the reference vertice dmax - the maximun distance. */ double vi[3], vj[3], d; int n=0, nf, fid; MAP status_v; MAP status_f; std::queue to_visit; vtkIdList* near_vertices = vtkIdList::New(); vtkIdList* idfaces = vtkIdList::New(); pd->GetPoint(v, vi); // The position of vertex v while (1) { pd->GetPointCells(v, idfaces); nf = idfaces->GetNumberOfIds(); for(int nid=0; nid < nf; nid++) { fid = idfaces->GetId(nid); if (status_f.find(fid) != status_f.end()) { if (to_visit.empty()) break; v = to_visit.front(); to_visit.pop(); continue; } status_f[fid] = true; vtkCell* face = pd->GetCell(fid); for(int i=0; i < 3; i++) { int vjid = face->GetPointId(i); if (status_v.find(vjid) == status_v.end() || !status_v[vjid]) { pd->GetPoint(vjid, vj); d = sqrt((vi[0] - vj[0]) * (vi[0] - vj[0])\ + (vi[1] - vj[1]) * (vi[1] - vj[1])\ + (vi[2] - vj[2]) * (vi[2] - vj[2])); if (d <= dmax) { near_vertices->InsertNextId(vjid); to_visit.push(vjid); } } status_v[vjid] = true; } } n++; if (to_visit.empty()) break; v = to_visit.front(); to_visit.pop(); idfaces->Reset(); } return near_vertices; } vtkDoubleArray* calc_artifacts_weight(vtkPolyData* pd, vtkIdList* vertices_staircase, double tmax, double bmin) { /* Calculate the artifact weight based on distance of each vertex to its nearest staircase artifact vertex. pd - vtkPolydata; vertices_staircase - the identified staircase artifact vertices; tmax=2 - max distance the vertex must be to its nearest artifact vertex to considered to calculate the weight; bmin=0.1 - The minimun weight. */ double vi[3], vj[3], d, value; int viid, vjid, nnv; int nid = vertices_staircase->GetNumberOfIds(); vtkIdList* near_vertices; vtkDoubleArray* weights = vtkDoubleArray::New(); for (int i=0; i < pd->GetNumberOfPoints(); i++){ weights->InsertNextValue(0); } for (int i=0; i < nid; i++) { viid = vertices_staircase->GetId(i); pd->GetPoint(viid, vi); near_vertices = get_near_vertices_to_v(pd, viid, tmax); nnv = near_vertices->GetNumberOfIds(); for (int j=0; j < nnv; j++){ vjid = near_vertices->GetId(j); pd->GetPoint(vjid, vj); d = sqrt((vi[0] - vj[0]) * (vi[0] - vj[0])\ + (vi[1] - vj[1]) * (vi[1] - vj[1])\ + (vi[2] - vj[2]) * (vi[2] - vj[2])); value = (1.0 - d/tmax) * (1 - bmin) + bmin; if (value > weights->GetValue(vjid)) { weights->SetValue(vjid, value); } } near_vertices->Delete(); } return weights; } Point calc_d(vtkPolyData* pd, int vid){ Point D; int nf, fid, n=0; double vi[3], vj[3]; std::set vertices; std::set::iterator it; vtkIdList* idfaces = vtkIdList::New(); pd->GetPointCells(vid, idfaces); nf = idfaces->GetNumberOfIds(); for (int nid=0; nid < nf; nid++) { fid = idfaces->GetId(nid); vtkCell* face = pd->GetCell(fid); for (int i=0; i < 3; i++) { int vjid = face->GetPointId(i); if (vjid != vid) vertices.insert(vjid); } } idfaces->Delete(); D.x = 0; D.y = 0; D.z = 0; pd->GetPoint(vid, vi); // The position of vertex v for (it=vertices.begin(); it!=vertices.end(); it++) { pd->GetPoint(*it, vj); D.x = D.x + (vi[0] - vj[0]); D.y = D.y + (vi[1] - vj[1]); D.z = D.z + (vi[2] - vj[2]); n++; } D.x = D.x / n; D.y = D.y / n; D.z = D.z / n; return D; } vtkPolyData* taubin_smooth(vtkPolyData* pd, vtkDoubleArray* weights, double l, double m, int steps){ /* * Implementation of Taubin's smooth algorithm described in the paper "A * Signal Processing Approach To Fair Surface Design". His benefeat is it * avoids to * */ double vi[3]; vtkPolyData* new_pd = vtkPolyData::New(); new_pd->DeepCopy(pd); //std::vector D(pd->GetNumberOfPoints()); //D.reserve(pd->GetNumberOfPoints()); Point *D; D = (Point*) malloc(pd->GetNumberOfPoints() * sizeof(Point)); for (int s=0; s < steps; s++) { printf("Step %d\n", s); for (int i=0; i < pd->GetNumberOfPoints(); i++) { D[i] = calc_d(new_pd, i); } for (int i=0; i < pd->GetNumberOfPoints(); i++) { new_pd->GetPoint(i, vi); vi[0] = vi[0] + weights->GetValue(i)*l*D[i].x; vi[1] = vi[1] + weights->GetValue(i)*l*D[i].y; vi[2] = vi[2] + weights->GetValue(i)*l*D[i].z; new_pd->GetPoints()->SetPoint(i, vi); } for (int i=0; i < pd->GetNumberOfPoints(); i++) { D[i] = calc_d(new_pd, i); } for (int i=0; i < pd->GetNumberOfPoints(); i++) { new_pd->GetPoint(i, vi); vi[0] = vi[0] + weights->GetValue(i)*m*D[i].x; vi[1] = vi[1] + weights->GetValue(i)*m*D[i].y; vi[2] = vi[2] + weights->GetValue(i)*m*D[i].z; new_pd->GetPoints()->SetPoint(i, vi); } } free(D); return new_pd; } MAP > get_flat_areas(vtkPolyData* pd, double stack_orientation[3], double tmax, int msize) { /* Returns each flat area in the given *vtkPolydata pd*. To be considered a * flat area it must have normal bellow *tmax* related to the * *stack_orientation* and have at least *msize* triangles. The result is * returned as hash_map. */ MAP > flat_areas; return flat_areas; } python-casmoothing-0.1/test_python_wrapper.py0000664000000000000000000000075312044363170020403 0ustar rootrootimport sys import vtk import ca_smoothing stl = vtk.vtkSTLReader() stl.SetFileName(sys.argv[1]) stl.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(stl.GetOutput()) normals.ComputeCellNormalsOn() normals.Update() clean = vtk.vtkCleanPolyData() clean.SetInput(normals.GetOutput()) clean.Update() pd = clean.GetOutput() pd.BuildLinks() tpd = ca_smoothing.ca_smoothing(pd, 0.7, 3, 0.2, 10) ply = vtk.vtkPLYWriter() ply.SetFileName(sys.argv[2]) ply.SetInput(tpd) ply.Write() python-casmoothing-0.1/ca_smoothing.h0000664000000000000000000000517612044363170016540 0ustar rootroot//-------------------------------------------------------------------------- // Software: Context Aware Smoothing // Copyright: (C) 2012 Centro de Pesquisas Renato Archer // Homepage: https://github.com/tfmoraes/context_aware_smoothing // Contact: tfmoraes@cti.gov.br // License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) //-------------------------------------------------------------------------- // Este programa e software livre; voce pode redistribui-lo e/ou // modifica-lo sob os termos da Licenca Publica Geral GNU, conforme // publicada pela Free Software Foundation; de acordo com a versao 2 // da Licenca. // // Este programa eh distribuido na expectativa de ser util, mas SEM // QUALQUER GARANTIA; sem mesmo a garantia implicita de // COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM // PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais // detalhes. //-------------------------------------------------------------------------- #include #ifdef HAVE_CXX0X #include #define MAP std::unordered_map #elif HAVE_TR1 #include #define MAP std::tr1::unordered_map #else #include #define MAP std::map #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include typedef struct _Point { double x; double y; double z; } Point; vtkPolyData* ca_smoothing (vtkPolyData*, double, double, double, int); vtkIdList* find_staircase_artifacts(vtkPolyData*, const double[3], double); vtkIdList* get_near_vertices_to_v(vtkPolyData*, int, double); vtkDoubleArray* calc_artifacts_weight(vtkPolyData*, vtkIdList*, double, double); Point calc_d(vtkPolyData*, int); vtkPolyData* taubin_smooth(vtkPolyData*, vtkDoubleArray*, double, double, int); MAP > get_flat_areas(vtkPolyData*, double[3], double); python-casmoothing-0.1/LICENSE.txt0000755000000000000000000004303412044363170015534 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. python-casmoothing-0.1/CMakeLists.txt0000664000000000000000000000506512044363170016452 0ustar rootrootcmake_minimum_required(VERSION 2.6) INCLUDE(CPack) INCLUDE(CheckIncludeFile) INCLUDE(CheckIncludeFileCXX) INCLUDE(CheckFunctionExists) PROJECT(ca_smoothing) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) find_package(VTK REQUIRED) include(${VTK_USE_FILE}) FIND_PACKAGE(SWIG REQUIRED) INCLUDE(${SWIG_USE_FILE}) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) #add_library(ca_smoothing SHARED ca_smoothing.cxx) #add_executable(ca_smoothing_app ca_smoothing_app.cxx) SET (Libraries vtkPythonCore) SET_SOURCE_FILES_PROPERTIES(ca_smoothing.i PROPERTIES CPLUSPLUS ON) #SET_SOURCE_FILES_PROPERTIES(ca_smoothing.i PROPERTIES SWIG_FLAGS "-includeall") set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}/lib) SWIG_ADD_MODULE(ca_smoothing python ca_smoothing.i ca_smoothing.cxx) message(STATUS "Libraries" ${Libraries}) if(VTK_LIBRARIES) #target_link_libraries(ca_smoothing ${VTK_LIBRARIES} ${Libraries}) #target_link_libraries(ca_smoothing_app ca_smoothing ${VTK_LIBRARIES} ${Libraries}) SWIG_LINK_LIBRARIES(ca_smoothing ${PYTHON_LIBRARIES} ${Libraries} ${VTK_LIBRARIES}) else() #target_link_libraries(ca_smoothing vtkHybrid ) #target_link_libraries(ca_smoothing_app ca_smoothing vtkHybrid ${Libraries}) SWIG_LINK_LIBRARIES(ca_smoothing ${PYTHON_LIBRARIES} vtkHybrid vtkCommon vtkHybridPythonD vtkFiltering) endif() IF (CMAKE_COMPILER_IS_GNUCXX) set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") # If g++ is greater than 4.6, set to use c++0x standard. execute_process(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GXX_VERSION) if(GXX_VERSION VERSION_GREATER "4.6") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") endif(GXX_VERSION VERSION_GREATER "4.6") ENDIF(CMAKE_COMPILER_IS_GNUCXX) CHECK_INCLUDE_FILE_CXX (unordered_map HAVE_CXX0X) CHECK_INCLUDE_FILE_CXX (tr1/unordered_map HAVE_TR1) IF (NOT HAVE_CXX0X) SET (HAVE_CXX0X 0) ENDIF (NOT HAVE_CXX0X) IF (NOT HAVE_TR1) SET (HAVE_TR1 0) ENDIF (NOT HAVE_TR1) # Finding python site-packages dir execute_process( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib(prefix='')" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE ) INSTALL(TARGETS _ca_smoothing DESTINATION ${CMAKE_INSTALL_PREFIX}/${PYTHON_SITE_PACKAGES}) INSTALL(FILES ${CMAKE_BINARY_DIR}/lib/ca_smoothing.py DESTINATION ${CMAKE_INSTALL_PREFIX}/${PYTHON_SITE_PACKAGES}) python-casmoothing-0.1/ca_smoothing.i0000664000000000000000000000254312044363170016534 0ustar rootroot%module ca_smoothing /*%include "ca_smoothing.h"*/ %include exception.i // Common stuff #include "vtkObjectBase.h" #include "vtkObject.h" #include "vtkPolyData.h" %include cpointer.i %pointer_functions(int, intp); %pointer_functions(float, floatp); %pointer_functions (double, doublep); %pointer_functions (bool, boolp); /*%typemap(cstype) vtkPolyData * "vtkPolyData"*/ /*%typemap(csin) vtkPolyData * "$csinput.GetCppThis()"*/ /*%typemap(csout) (vtkPolyData*) {*/ /*IntPtr rawCppThisSwig = $imcall;*/ /*vtkPolyData data = new vtkPolyData( rawCppThisSwig, false, false );*/ /*return data;*/ /*}*/ %{ #include "vtkPythonUtil.h" #include "vtkPolyData.h" #if (VTK_MAJOR_VERSION > 5 ||((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION > 6))) #define vtkPythonGetObjectFromPointer vtkPythonUtil::GetObjectFromPointer #define vtkPythonGetPointerFromObject vtkPythonUtil::GetPointerFromObject #endif %} %typemap(out) vtkPolyData* { PyImport_ImportModule("vtk"); $result = vtkPythonGetObjectFromPointer( (vtkPolyData*)$1 ); } %typemap(in) vtkPolyData* { $1 = NULL; $1 = (vtkPolyData*) vtkPythonGetPointerFromObject ( $input, "vtkPolyData" ); if ( $1 == NULL ) { SWIG_fail; } } extern vtkPolyData* ca_smoothing (vtkPolyData*, double, double, double, int); %{ #include "stdio.h" #include "math.h" #include "ca_smoothing.h" %} python-casmoothing-0.1/AUTHORS.txt0000755000000000000000000000016712044363170015577 0ustar rootrootThe PRIMARY AUTHORS of "context aware smoothing" python library are (and/or have been): * Thiago Franco de Moraes