Esempio n. 1
0
int check_eswc_toolbox(const V3DPluginArgList & input)
{
	vaa3d_neurontoolbox_paras * paras = (vaa3d_neurontoolbox_paras *)(input.at(0).p);
	NeuronTree neuron = paras->nt;
	QString fileOpenName = neuron.file;
	
	vector<V3DLONG> segment_id, segment_layer;
	vector<double> feature;
	if (fileOpenName.endsWith(".eswc") || fileOpenName.endsWith(".ESWC"))
		neuron = read_eswc(segment_id, segment_layer, feature, fileOpenName);
	else {
		v3d_msg("The file type you specified is not in eswc format. Please check.");
		return -1;
	}

	int check_result = check_eswc(neuron, segment_id, segment_layer);
	if (check_result==-1 || check_result==0)
	{
		QMessageBox msgBox;
		if (check_result==-1)
			msgBox.setText("Something is wrong with the eswc file.");
		else
			msgBox.setText("Your eswc is written in default values.");
		msgBox.setInformativeText("Do you still want to overwrite it with a standard one?");
		msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Cancel);
		if (msgBox.exec()==QMessageBox::Yes)
		{
			swc2eswc(neuron, segment_id, segment_layer);
			export_eswc(neuron, segment_id, segment_layer, qPrintable(fileOpenName), qPrintable(fileOpenName));
		v3d_msg(QString("%1 has been updated!").arg(fileOpenName));
		}
		else return -1;
	}
	else
		v3d_msg("Your eswc file is in correct format!");

	return 1;
}
Esempio n. 2
0
void NEURONSEGlugin::domenu(const QString &menu_name, V3DPluginCallback &callback, QWidget *parent)
{
	if (menu_name == tr("Swc segment"))
	{
		swc_to_segments(callback, parent,1);
		
	}
	else if (menu_name == tr("Help"))
	{
		v3d_msg("(version 0.11)Neuronseg Plugin 1.0 developed by Jinzhu Yang. (Peng Lab, Janelia Research Farm Campus, HHMI), save swc files according to different segments of swc file");
		return;
	}
}
Esempio n. 3
0
int swc2eswc_toolbox(const V3DPluginArgList & input)
{
	vaa3d_neurontoolbox_paras * paras = (vaa3d_neurontoolbox_paras *)(input.at(0).p);
	NeuronTree neuron = paras->nt;
	QString fileOpenName = neuron.file;
	
	vector<V3DLONG> segment_id, segment_layer;
	if (fileOpenName.endsWith(".swc") || fileOpenName.endsWith(".SWC"))
	{
		segment_id, segment_layer;
		if (!swc2eswc(neuron,segment_id, segment_layer))
		{
			v3d_msg("Cannot convert swc to eswc.\n");
			return -1;
		}
	}
	else {
		v3d_msg("The file type you specified is not in swc format. Please check.");
		return -1;
	}
	
	QString fileDefaultName = fileOpenName;
	fileDefaultName.chop(3);
	fileDefaultName += QString("eswc");
	//write new SWC to file
	QString fileSaveName = QFileDialog::getSaveFileName(0, QObject::tr("Save File"),
			fileDefaultName,
			QObject::tr("Supported file (*.eswc)"
				";;Extended Neuron structure	(*.eswc)"
				));
	if (!export_eswc(neuron,segment_id,segment_layer,qPrintable(fileOpenName),qPrintable(fileSaveName)))
	{
		v3d_msg("fail to write the output eswc file.");
		return -1;
	}
	return 1;
}
Esempio n. 4
0
void combiner::is_dialog_ok_clicked()
{
    //check number of files.
    //close window
    if (load_is_combo->count()>0)
    {
        load_is_dialog->close();
        edit_is->setText(QString::number(load_is_combo->count())+" csv file(s) selected");
        check_button();
    }
    else
    {
        v3d_msg("No files selected. Please select");
    }
}
Esempio n. 5
0
void BWLabelNPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
    if (menu_name == tr("3D"))
    {
    	bwlabelimg(callback, parent, 3); //3 - 3D
    }
	else if (menu_name == tr("2D (for all individual Z-sections)"))
	{
    	bwlabelimg(callback, parent, 2); //2 - 2D
	}
	else if (menu_name == tr("about"))
	{
    	v3d_msg(QString("This plugin thresholds an image and then labels all image objects. Developed by Hanchuan Peng, by wrapping Fuhui Long's original code. (version %1)").arg(getPluginVersion())); 
	}
}
void neuron_tipspicker_dialog::output_markers(QString fname)
{
    QFile file(fname);
    if (!file.open(QIODevice::WriteOnly|QIODevice::Text)){
        v3d_msg("cannot open "+ fname +" for write");
        return;
    }
    QTextStream myfile(&file);
    myfile<<"##x,y,z,radius,shape,name,comment, color_r,color_g,color_b"<<endl;
    //matched candidates first
    int info[4];
    for(int i=0; i<mList->size(); i++){
        get_marker_info(mList->at(i), info);
        if(info[2]==1)
            myfile<<mList->at(i).x<<","<<mList->at(i).y<<","<<mList->at(i).z<<",0,1, , ,0,255,0"<<endl;
    }
    file.close();
}
void MovieFrom3Dviewer(V3DPluginCallback2 & v3d, QWidget * parent)
{
	v3dhandle curwin = v3d.currentImageWindow();
	if (!curwin)
	{
		v3d_msg("You don't have any image open in the main window.");
		return;
	}
	v3d.open3DWindow(curwin);

	if (controlPanel::m_pLookPanel)
	{
		controlPanel::m_pLookPanel->show();
		return;
	}

	controlPanel* p = new controlPanel(v3d, parent);
	if (p)	p->show();
}
void neuron_tipspicker_dialog::checkStatus()
{
    if(cb_tips->count()>mList->size()){
        v3d_msg("The number of markers does not match, please click Update or Reload button.");
        cb_tips->setEnabled(false);
        btn_accept->setEnabled(false);
        btn_skip->setEnabled(false);
        btn_reject->setEnabled(false);
    }else if(cb_tips->count()>0){
        cb_tips->setEnabled(true);
        btn_accept->setEnabled(true);
        btn_skip->setEnabled(true);
        btn_reject->setEnabled(true);
    }else{
        btn_accept->setEnabled(false);
        btn_skip->setEnabled(false);
        btn_reject->setEnabled(false);
    }
}
// build atlas
void fl_procPC_Atlas_build_atlas(atlasConfig & cfginfo)
{
    
    apoAtlasBuilderInfo atlasbuiderinfo;
	
    fl_func_procIO_build_atlas(atlasbuiderinfo);
    
    apoAtlasLinkerInfoAll apoinfo;
    
    if (atlasbuiderinfo.linkerFileName.compare("")!=0) // otherwise, you have selected cancel, no need to merge
    {
//        atlasbuiderinfo.linkerFileName.append("/");
        fl_func_procCompute_build_atlas(atlasbuiderinfo, cfginfo, apoinfo);
//        v3d_msg("Results can be found in the output folder that you've set up through adjust preference function. End of coexpression merging.");
    }
    else
        v3d_msg("You canceled atlas building function. No results generated. End of atlas building.");  

    
}
void fl_procPC_atlas_detect_coexpress_cells(atlasConfig & cfginfo)
{
    
    apoAtlasCoexpressionDetect apoCoExpressInfo;
    
    fl_func_procIO_detect_coexpress_cells(apoCoExpressInfo, cfginfo);
    
    for (int i=0; i<apoCoExpressInfo.apoAtlasFilelist.size(); i++)
        printf("%s\n", qPrintable(apoCoExpressInfo.apoAtlasFilelist.at(i)));
    printf("%s\n", qPrintable(apoCoExpressInfo.coExpressionOutputFilePrefix));
    
    if (apoCoExpressInfo.coExpressionOutputFilePrefix.compare("")!=0)
        fl_func_procCompute_atlas_detect_coexpress_cells(apoCoExpressInfo, cfginfo);
    
//    v3d_msg("The coexpression files have been generated [fl_procPC_atlas_detect_coexpress_cells() done].");
    v3d_msg("End of coexpression detection.");
  
    
    
}
void SnapShoot3Dviewer(V3DPluginCallback2 & v3d, QWidget * parent)
{
	v3dhandle curwin = v3d.currentImageWindow();
	if (!curwin)
	{
		v3d_msg("You don't have any image opened in the main window.");
		return;
	}
	v3d.open3DWindow(curwin);

	QFileDialog d(parent);
	d.setWindowTitle(QObject::tr("Choose output snapshot filename"));
	d.setAcceptMode(QFileDialog::AcceptSave);
	if (!d.exec()) return;

	QString BMPfilename = (d.selectedFiles())[0];
	if (BMPfilename.endsWith(".BMP", Qt::CaseInsensitive))
	   BMPfilename.resize(BMPfilename.length()-4); //by PHC
	v3d.screenShot3DWindow(curwin, BMPfilename);
	QMessageBox::information(0, title, QString("Snapshot was saved to: %1.BMP\n").arg(BMPfilename));
}
Esempio n. 12
0
bool v3d_imaging(MainWindow* mainwindow, const v3d_imaging_paras & p)
{
	v3d_msg(QString("Now try to do imaging or other plugin functions [%1]").arg(p.OPS), 0);
	
	try 
	{
		const char* filename=p.imgp->getFileName();
        //v3d_msg(QString("[")+filename+"]");
        XFormWidget *curw = 0;
        if (filename)
        {
            curw = mainwindow->findMdiChild(QString(filename)); //search window using name. ZJL
            //unsigned char* rawdata=p.imgp->getRawData();
            //QList <V3dR_MainWindow *> winlist=mainwindow->list_3Dview_win;
            //V3dR_MainWindow *curwin;
            //for(int i=0;i<winlist.size();i++)
            //{
            //	unsigned char* winrawdata=winlist.at(i)->getGLWidget()->getiDrawExternalParameter()->image4d->getRawData();
            //	if(rawdata==winrawdata)
            //	{
            //		curwin=winlist.at(i);
            //		continue;
            //	}
            //}
            if (!curw)
            {
                v3d_msg(QString("No window open yet (error detected in v3d_imaging() main entry point [filename={%1}]).").arg(filename));
                return false;
            }
        }
        else
        {
            if (p.OPS != "Load file using Vaa3D data IO manager") //only allow data IO manager to pass an empty file name parameter here
                return false;
        }


		QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
		if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
			pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
		if (pluginsDir.dirName() == "MacOS") {
			pluginsDir.cdUp();
			pluginsDir.cdUp();
			pluginsDir.cdUp();
		}
#endif
        if (p.OPS == "Vaa3D-Neuron2-APP2")
        {
            if (pluginsDir.cd("plugins/neuron_tracing/Vaa3D_Neuron2")==false)
            {
                v3d_msg("Cannot find ./plugins/neuron_tracing/Vaa3D_Neuron2 directory!");
                return false;
            }            
        }
        else if (p.OPS == "Fetch Highrez Image Data from File")
        {
            // @FIXED by Alessandro on 2015-09-30.
            // Since TeraFly is part of Vaa3D, here we can directly call TeraFly's domenu function w/o using QPluginLoader.
            curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin
            tf::TeraFly::doaction(p.OPS);
            return true;
        }
        else if (p.OPS == "Load file using Vaa3D data IO manager")
        {
            if (pluginsDir.cd("plugins/data_IO/data_IO_manager")==false)
            {
                v3d_msg("Cannot find ./plugins/data_IO/data_IO_manager directory!");
                return false;
            }
        }
        else
        {
            if (pluginsDir.cd("plugins/smartscope_controller")==false) 
            {
                v3d_msg("Cannot find ./plugins/smartscope_controller directory!");
                return false;
            }
        }
		
		QStringList fileList = pluginsDir.entryList(QDir::Files);
		if (fileList.size()<1)
		{
			v3d_msg("Cannot find any file in the ./plugins/smartscope_controller directory!");
			return false;
		}
		
		QString fullpath = pluginsDir.absoluteFilePath(fileList.at(0)); //always just use the first file (assume it is the only one) found in the folder as the "correct" dll
		//the real dll name should be "microimaging.dll"
		
    	QPluginLoader* loader = new QPluginLoader(fullpath);
        if (!loader)
        {
        	qDebug("ERROR in V3d_PluginLoader::searchPluginFiles the imaging module(%s)", qPrintable(fullpath));
        	return false;
        }
		
		v3d_msg(fullpath, 0);
		
		V3d_PluginLoader mypluginloader(mainwindow);

        if (curw)
        {
            //mypluginloader.runPlugin(loader, QString("about this plugin"));
            curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin

            QTime t;
            t.start();
            mypluginloader.runPlugin(loader, p.OPS);
            //mypluginloader.runPlugin(loader, "about");
            v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0);
        }
        else //for data IO manager in which case curw is NULL
        {
            QTime t;
            t.start();
            mypluginloader.runPlugin(loader, p.datafilename); //the data IO manager is specially designed to pass the datafilename parameter in this way. 2013-12-02. by PHC. what an ugly design here!
            v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0);
        }
	}
	catch (...)
	{
		v3d_msg("Catch a problem in v3d_imaging() wrapper function.", 1);
		return false;
	}
	
	return true;
}
Esempio n. 13
0
bool load_data(V3DPluginCallback2 *cb,unsigned char * & image1Dc_in,LandmarkList &LList,ImagePixelType &pixeltype,
               V3DLONG sz_img[4],v3dhandle &curwin)
{
    V3DPluginCallback2 *callback=cb;
    v3dhandleList v3dhandleList_current=callback->getImageWindowList();
    QList <V3dR_MainWindow *> cur_list_3dviewer = callback->getListAll3DViewers();
    LandmarkList LList_in;

    if (v3dhandleList_current.size()==0){
        v3d_msg("Please open image and select markers");
        return false;
    }
    else if (v3dhandleList_current.size()==1)  //One window open
    {
        //get markers and check markers
        LList_in.clear();
        LList_in = callback->getLandmark(v3dhandleList_current[0]);
        if (LList_in.size()==0)
        {
            v3d_msg("Please load markers");
            return false;
        }
        curwin=v3dhandleList_current[0];
    }
    else if (v3dhandleList_current.size()>1)
    {
        QStringList items;
        int i;
        for (i=0; i<v3dhandleList_current.size(); i++)
            items << callback->getImageName(v3dhandleList_current[i]);

        for (i=0; i<cur_list_3dviewer.count(); i++)
        {
            QString curname = callback->getImageName(cur_list_3dviewer[i]).remove("3D View [").remove("]");
            bool b_found=false;
            for (int j=0; j<v3dhandleList_current.size(); j++)
                if (curname==callback->getImageName(v3dhandleList_current[j]))
                {
                    b_found=true;
                    break;
                }

            if (!b_found)
                items << callback->getImageName(cur_list_3dviewer[i]);
        }
        //qDebug()<<"Number of items:"<<items.size();

        QDialog *mydialog=new QDialog;
        QComboBox *combo=new QComboBox;
        combo->insertItems(0,items);
        QLabel *label_win=new QLabel;
        label_win->setText("You have multiple windows open, please select one image:");
        QGridLayout *layout= new QGridLayout;
        layout->addWidget(label_win,0,0,1,1);
        layout->addWidget(combo,1,0,4,1);
        QPushButton *button_d_ok=new QPushButton("Ok");
        button_d_ok->setFixedWidth(100);
        QPushButton *button_d_cancel=new QPushButton("Cancel");
        button_d_cancel->setFixedWidth(100);
        QHBoxLayout *box=new QHBoxLayout;
        box->addWidget(button_d_ok,Qt::AlignCenter);
        box->addWidget(button_d_cancel,Qt::AlignCenter);
        layout->addLayout(box,5,0,1,1);
        QDialog::connect(button_d_ok,SIGNAL(clicked()),mydialog,SLOT(accept()));
        QDialog::connect(button_d_cancel,SIGNAL(clicked()),mydialog,SLOT(reject()));

        mydialog->setLayout(layout);
        mydialog->exec();
        if (mydialog->result()==QDialog::Accepted)
        {
            int tmp=combo->currentIndex();
            curwin=v3dhandleList_current[tmp];
        }
        else
        {
            v3d_msg("You have not selected a window");
            return false;
        }
        //get markers and check markers
        LList_in.clear();
        LList_in = callback->getLandmark(curwin);
        if (LList_in.size()==0)
        {
            v3d_msg("Please load markers");
            return false;
        }
    }

    //Get the image info
    Image4DSimple* p4DImage = callback->getImage(curwin);
    if (!p4DImage){
        QMessageBox::information(0, "", "The image pointer is invalid. Ensure your data is valid and try again!");
        return false;
    }

    sz_img[0]=p4DImage->getXDim();
    sz_img[1]=p4DImage->getYDim();
    sz_img[2]=p4DImage->getZDim();
    sz_img[3]=p4DImage->getCDim();

    if (sz_img[3]>3){
        sz_img[3]=3;
        QMessageBox::information(0,"","More than 3 channels were loaded."
                                 "The first 3 channel will be applied for analysis.");
    }

    V3DLONG size_tmp=sz_img[0]*sz_img[1]*sz_img[2]*sz_img[3];
    pixeltype = p4DImage->getDatatype();
    image1Dc_in=memory_allocate_uchar1D(size_tmp);
    unsigned char * ptmp=p4DImage->getRawData();
    memcpy(image1Dc_in,ptmp,size_tmp*pixeltype);

    LList.clear();
    for(int i=0; i<LList_in.size(); i++){
        LList.append(LList_in.at(i));
        LList[i].color.r=196;
        LList[i].color.g=LList[i].color.b=0;
    }
    return true;
}
Esempio n. 14
0
vector<float> calc_mean_shift_center(V3DLONG ind, int windowradius,float *data1Dc_float,
                                     V3DLONG sz_image[],int methodcode)
{
    //qDebug()<<"methodcode:"<<methodcode;
    V3DLONG y_offset=sz_image[0];
    V3DLONG z_offset=sz_image[0]*sz_image[1];
    V3DLONG page_size=sz_image[0]*sz_image[1]*sz_image[2];

    V3DLONG pos;
    vector<V3DLONG> coord;

    float total_x,total_y,total_z,v_color,sum_v,v_prev,x,y,z;
    float center_dis=1;
    vector<float> center_float(3,0);

    coord=pos2xyz(ind, y_offset, z_offset);
    x=(float)coord[0];y=(float)coord[1];z=(float)coord[2];
    //qDebug()<<"x,y,z:"<<x<<":"<<y<<":"<<z<<"ind:"<<ind;

    //find out the channel with the maximum intensity for the marker
    v_prev=data1Dc_float[ind];
    int channel=0;
    for (int j=1;j<sz_image[3];j++)
    {
        if (data1Dc_float[ind+page_size*j]>v_prev)
        {
            v_prev=data1Dc_float[ind+page_size*j];
            channel=j;
        }
    }
    //qDebug()<<"v_Prev:"<<v_prev;
    int testCount=0;
    int testCount1=0;

    while (center_dis>=0.5)
    {
        total_x=total_y=total_z=sum_v=0;

        testCount=testCount1=0;

        for(V3DLONG dx=MAX(x+0.5-windowradius,0); dx<=MIN(sz_image[0]-1,x+0.5+windowradius); dx++){
            for(V3DLONG dy=MAX(y+0.5-windowradius,0); dy<=MIN(sz_image[1]-1,y+0.5+windowradius); dy++){
                for(V3DLONG dz=MAX(z+0.5-windowradius,0); dz<=MIN(sz_image[2]-1,z+0.5+windowradius); dz++){
                    pos=xyz2pos(dx,dy,dz,y_offset,z_offset);
                    double tmp=(dx-x)*(dx-x)+(dy-y)*(dy-y)
                         +(dz-z)*(dz-z);
                    double distance=sqrt(tmp);
                    if (distance>windowradius) continue;
                    v_color=data1Dc_float[pos+page_size*channel];

                    total_x=v_color*(float)dx+total_x;
                    total_y=v_color*(float)dy+total_y;
                    total_z=v_color*(float)dz+total_z;
                    sum_v=sum_v+v_color;

                    testCount++;
                    if(v_color>100)
                        testCount1++;
                 }
             }
         }
        //qDebug()<<"windowradius:"<<windowradius;
        //qDebug()<<"total xyz:"<<total_x<<":"<<total_y<<":"<<total_z<<":"<<sum_v<<":"<<sum_v/testCount<<":"<<testCount<<":"<<testCount1;

        center_float[0]=total_x/sum_v;
        center_float[1]=total_y/sum_v;
        center_float[2]=total_z/sum_v;

        if (total_x<1e-5||total_y<1e-5||total_z<1e-5) //a very dark marker.
        {

            v3d_msg("Sphere surrounding the marker is zero. Mean-shift cannot happen. Marker location will not move",0);
            center_float[0]=x;
            center_float[1]=y;
            center_float[2]=z;
            return center_float;
        }

        V3DLONG prev_ind=xyz2pos((int)(x+0.5),(int)(y+0.5),(int)(z+0.5),y_offset,z_offset);
        V3DLONG tmp_ind=xyz2pos((int)(center_float[0]+0.5),(int)(center_float[1]+0.5),(int)(center_float[2]+0.5),
                y_offset,z_offset);

        if (methodcode==2)
        {
            if (data1Dc_float[tmp_ind+channel*page_size]<data1Dc_float[prev_ind+channel*page_size]&& windowradius>=2) // && windowradius>2)
            {
            //qDebug()<<methodcode<<" window too large"<<windowradius;
            windowradius--;
            center_dis=1;
            continue;
            }
         }

        float tmp_1=(center_float[0]-x)*(center_float[0]-x)+(center_float[1]-y)*(center_float[1]-y)
                    +(center_float[2]-z)*(center_float[2]-z);
        center_dis=sqrt(tmp_1);

        //qDebug()<<"new_center:"<<center_float[0]<<":"<<center_float[1]<<":"<<center_float[2]<<" intensity:"<<data1Dc_float[tmp_ind+channel*page_size];
        //qDebug()<<"center distance:"<<center_dis;
        x=center_float[0]; y=center_float[1]; z=center_float[2];
    }

    return center_float;
}
Esempio n. 15
0
vector<float> mean_shift_fun::ray_shoot_center(V3DLONG ind,int bg_thr,int j)
{
    V3DLONG y_offset=sz_image[0];
    V3DLONG z_offset=sz_image[0]*sz_image[1];

    V3DLONG pos,pos_prev;
    vector<V3DLONG> coord;
    float dir_vec[48][3]={{0.6667,0.6667,0.3333},{0.2852,0.6886,0.6667},{0.6886,0.2852,0.6667},
                        {0.2826,0.2826,0.9167},{-0.6667,0.6667,0.3333},{-0.6886,0.2852,0.6667},
                        {-0.2852,0.6886,0.6667},{-0.2826,0.2826,0.9167},{-0.6667,-0.6667,0.3333},
                        {-0.2852,-0.6886,0.6667},{-0.6886,-0.2852,0.6667},{-0.2826,-0.2826,0.9167},
                        {0.6667,-0.6667,0.3333},{0.6886,-0.2852,0.6667},{0.2852,-0.6886,0.6667},
                        {0.2826,-0.2826,0.9167},{0.9428,0.0000,-0.3333},{0.9239,0.3827,0.0000},
                        {0.9239,-0.3827,0.0000},{0.9428,0.0000,0.3333},{0.0000,0.9428,-0.3333},
                        {-0.3827,0.9239,0.0000},{0.3827,0.9239,0.0000},{0.0000,0.9428,0.3333},
                        {-0.9428,0.0000,-0.3333},{-0.9239,-0.3827,0.0000},{-0.9239,0.3827,0.0000},
                        {-0.9428,0.0000,0.3333},{0.0000,-0.9428,-0.3333},{0.3827,-0.9239,0.0000},
                        {-0.3827,-0.9239,0.0000},{0.0000,-0.9428,0.3333},{0.2826,0.2826,-0.9167},
                        {0.2852,0.6886,-0.6667},{0.6886,0.2852,-0.6667},{0.6667,0.6667,-0.3333},
                        {-0.2826,0.2826,-0.9167},{-0.6886,0.2852,-0.6667},{-0.2852,0.6886,-0.6667},
                        {-0.6667,0.6667,-0.3333},{-0.2826,-0.2826,-0.9167},{-0.2852,-0.6886,-0.6667},
                        {-0.6886,-0.2852,-0.6667},{-0.6667,-0.6667,-0.3333},{0.2826,-0.2826,-0.9167},
                        {0.6886,-0.2852,-0.6667},{0.2852,-0.6886,-0.6667},{0.6667,-0.6667,-0.3333}};

    int dir_vec_size=48;

    vector<float> center_float(3,0);
    vector<float> intensity_vec;
    float v_prev,v_new,x,y,z,x_new,y_new,z_new,sum_x,sum_y,sum_z,x_prev,y_prev,z_prev,dx_sum,dy_sum,dz_sum;
    float center_dis=1;
    float bound[48][3];
    coord=pos2xyz(ind, y_offset, z_offset);
    x=(float)coord[0];y=(float)coord[1];z=(float)coord[2];
    //qDebug()<<"x,y,z:"<<x<<":"<<y<<":"<<z;

    dx_sum=dy_sum=dz_sum=0;
    for (int k=0;k<dir_vec_size;k++)
    {
        dx_sum=dx_sum+ABS(dir_vec[k][0]);
        dy_sum=dy_sum+ABS(dir_vec[k][1]);
        dz_sum=dz_sum+ABS(dir_vec[k][2]);
    }

    //find out the channel with the maximum intensity for the marker
    v_prev=data1Dc_float[ind];
    int channel=0;
    for (int j=1;j<sz_image[3];j++)
    {
        if (data1Dc_float[ind+page_size*j]>v_prev)
        {
            v_prev=data1Dc_float[ind+page_size*j];
            channel=j;
        }
    }
//    QString myfile="record.txt";
//    FILE * fp1 = fopen(myfile.toLatin1(), "wt");
//    fprintf(fp1, "j=: %ld\n",j);
//    fprintf(fp1,"##dir_vect,x,y,z,intensity\n");

    float converge_dis=0.5;
    while (center_dis>converge_dis)
    {
        sum_x=sum_y=sum_z=0;

        for (int i=0;i<dir_vec_size;i++)
        {
            //qDebug()<<"new round";
            intensity_vec.clear();
            intensity_vec.push_back(v_prev);
            float dx=dir_vec[i][0];
            float dy=dir_vec[i][1];
            float dz=dir_vec[i][2];
            //qDebug()<<"dx,dy,dz:"<<dx<<":"<<dy<<":"<<dz;
            pos_prev=ind;
            x_prev=x;
            y_prev=y;
            z_prev=z;
            v_new=v_prev;

            while (v_new>bg_thr)
            {
                x_new=x_prev+dx;
                if (x_new<0 || x_new>sz_image[0]-1)
                {
                    y_new=y_prev+dy;
                    z_new=z_prev+dz;
                    //qDebug()<<"x touches edge";
                    break;
                }
                y_new=y_prev+dy;
                if (y_new<0 || y_new>sz_image[1]-1)
                {
                    z_new=z_prev+dz;
                    //qDebug()<<"y touches edge";
                    break;
                }
                z_new=z_prev+dz;
                if (z_new<0 || z_new>sz_image[2]-1)
                {
                    //qDebug()<<"z touches edge";
                    break;
                }
                pos=xyz2pos(x_new+0.5,y_new+0.5,z_new+0.5,y_offset,z_offset); //float to int
                v_new=data1Dc_float[pos+channel*page_size];
                x_prev=x_new;
                y_prev=y_new;
                z_prev=z_new;
                if (pos==pos_prev) continue;
                pos_prev=pos;
                intensity_vec.push_back(v_new);
                //qDebug()<<"dir i:"<<i<<" x,y,z:"<<x_prev<<":"<<y_prev<<":"<<":"<<z_prev<<":"<<"intensity:"<<v_new;

                //fprintf(fp1,"%1d %5.3f %5.3f %5.3f %4.1f \n",i,x_prev,y_prev,z_prev,v_new);
            }
            //qDebug()<<"intensity_vec size:"<<intensity_vec.size();
            //fprintf(fp1,"___________intensity_vec_size: %1d\n",intensity_vec.size());
            if (intensity_vec.size()>4)
            {
                int id;
                bool reverse=false;
                for (id=2;id<intensity_vec.size()-2;id++)
                {
                    if ((intensity_vec[id]<intensity_vec[id-1])&&(intensity_vec[id]<=intensity_vec[id-2]-9)
                      &&intensity_vec[id]<intensity_vec[id+1]&&intensity_vec[id]<=intensity_vec[id+2]-9)
                    {
                        //qDebug()<<"reversed order: "<<id;
                        bound[i][0]=x+id*dx;
                        bound[i][1]=y+id*dy;
                        bound[i][2]=z+id*dz;
                        sum_x=sum_x+ABS(dx)*bound[i][0];
                        sum_y=sum_y+ABS(dy)*bound[i][1];
                        sum_z=sum_z+ABS(dz)*bound[i][2];
                        reverse=true;
                        //fprintf(fp1,"reverse order %1d\n",id);
                        break;

                    }
                }
                if (!reverse)
                {
                    bound[i][0]=x_new-dx;
                    bound[i][1]=y_new-dy;
                    bound[i][2]=z_new-dz;
                    sum_x=sum_x+ABS(dx)*(x_new-dx);
                    sum_y=sum_y+ABS(dy)*(y_new-dy);
                    sum_z=sum_z+ABS(dz)*(z_new-dz);
                }

            }
            else
            {
                bound[i][0]=x_new-dx;
                bound[i][1]=y_new-dy;
                bound[i][2]=z_new-dz;
                //qDebug()<<"Out of loop";
                sum_x=sum_x+ABS(dx)*(x_new-dx);
                sum_y=sum_y+ABS(dy)*(y_new-dy);
                sum_z=sum_z+ABS(dz)*(z_new-dz);
            }

        }
        //qDebug()<<"bounds:"<<bound[0][0]<<":"<<bound[0][1]<<":"<<bound[0][2];
//        qDebug()<<"dx_sum,y,z:"<<dx_sum<<":"<<dy_sum<<":"<<dz_sum;
//        qDebug()<<"sum_x,y,z:"<<sum_x<<":"<<sum_y<<":"<<sum_z;
        if (sum_x<1e-5||sum_y<1e-5||sum_z<1e-5) //a very dark marker.
        {
            v3d_msg("marker "+QString::number(j+1)+ " is below background threshold. Ray shoot will not move"
                      "the location");
            center_float[0]=x;
            center_float[1]=y;
            center_float[2]=z;
            return center_float;
        }
        center_float[0]=(float)sum_x/dx_sum;
        center_float[1]=(float)sum_y/dy_sum;
        center_float[2]=(float)sum_z/dz_sum;


        float tmp_dis=(center_float[0]-x)*(center_float[0]-x)+(center_float[1]-y)*(center_float[1]-y)
                    +(center_float[2]-z)*(center_float[2]-z);
        center_dis=sqrt(tmp_dis);

        //qDebug()<<"new_center:"<<center_float[0]<<":"<<center_float[1]<<":"<<center_float[2];;
        //qDebug()<<"center distance:"<<center_dis;

        //fprintf(fp1,"center distance: %5.3f\n",center_dis);
        x=center_float[0]; y=center_float[1]; z=center_float[2];
        V3DLONG tmp_ind=xyz2pos((int)(center_float[0]+0.5),(int)(center_float[1]+0.5),(int)(center_float[2]+0.5),
                y_offset,z_offset);
        v_prev=data1Dc_float[tmp_ind+channel*page_size];

    }
    //fclose(fp1);
    //return center_float;
//    QString curFile = "result.swc";
//    qDebug()<<"writing file";
//    FILE * fp = fopen(curFile.toLatin1(), "a");
//    if (!fp)
//    {
//        v3d_msg("Could not open the file to save the neuron.");
//    }

//    fprintf(fp, "#name %s\n", qPrintable(QString("no name")));
//    fprintf(fp, "#comment %s\n", qPrintable(QString("no comment")));
//    fprintf(fp, "##n,type,x,y,z,radius,parent\n");
//    fprintf(fp, "%ld %d %5.3f %5.3f %5.3f %5.3f %ld\n",
//            1+j*49, 1, x, y, z, 1, -1);

//    for (int m=0+j*49;m<j*49+dir_vec_size; m++)
//    {
//        fprintf(fp, "%ld %d %5.3f %5.3f %5.3f %5.3f %ld\n",
//                m+2, 1, bound[m-j*49][0], bound[m-j*49][1], bound[m-j*49][2], 1, 1+j*49);
//    }

//    fclose(fp);
    return center_float;
}
color_render_ESWC_dialog::color_render_ESWC_dialog(V3DPluginCallback2 * cb, V3dR_MainWindow* inwin, int nid)
{
    v3dwin=inwin;
    callback=cb;

    //load neuron tree
    nt=(NeuronTree*)&(callback->getHandleNeuronTrees_Any3DViewer(v3dwin)->at(nid));
    feaNum=nt->listNeuron.at(0).fea_val.size();
    if(feaNum<=0.1){
        v3d_msg("Cannot identify feature value for the selected neuron");
        return;
    }
    //back up type
    bk_type.clear();
    for(int i=0; i<nt->listNeuron.size(); i++){
        bk_type.push_back(nt->listNeuron.at(i).type);
    }

    //create
    this->setWindowTitle(nt->file);
    cb_feature = new QComboBox();
    for(int i=0; i<feaNum; i++)
        cb_feature->addItem(QString::number(i+1));

    cb_colormap= new QComboBox();
    cb_colormap->addItem(QString("heatmap"));
    cb_colormap->addItem(QString("rainbow"));

    spin_min = new QDoubleSpinBox();
    spin_max = new QDoubleSpinBox();
    spin_black = new QDoubleSpinBox();
    spin_white = new QDoubleSpinBox();
    spin_meg = new QDoubleSpinBox();
    check_black = new QCheckBox("black threshold (<=)");
    check_white = new QCheckBox("white threshold (<=)");
    check_meg = new QCheckBox("magenta threshold (>=)");
    btn_update = new QPushButton("update");
    btn_quit = new QPushButton("quit");
    btn_reset = new QPushButton("reset");

    connect(check_black, SIGNAL(clicked()),this,SLOT(set_black()));
    connect(check_white, SIGNAL(clicked()),this,SLOT(set_white()));
    connect(check_meg, SIGNAL(clicked()),this,SLOT(set_magenta()));
    connect(btn_update, SIGNAL(clicked()),this,SLOT(update()));
    connect(btn_quit, SIGNAL(clicked()),this,SLOT(reject()));
    connect(btn_reset, SIGNAL(clicked()),this,SLOT(reset()));
    connect(cb_feature, SIGNAL(currentIndexChanged(int)),this,SLOT(set_span()));
    connect(cb_colormap, SIGNAL(currentIndexChanged(int)),this,SLOT(set_colormap()));

    //layout
    QGridLayout * gridLayout = new QGridLayout();

    QLabel* label_feature = new QLabel("feature id:");
    gridLayout->addWidget(label_feature,1,0,1,2);
    gridLayout->addWidget(cb_feature,1,2,1,1);

    QLabel* label_colormap= new QLabel("colormap:");
    gridLayout->addWidget(label_colormap,2,0,1,2);
    gridLayout->addWidget(cb_colormap,2,2,1,1);

    QLabel* label_min = new QLabel("color bar low:");
    gridLayout->addWidget(label_min,3,0,1,2);
    gridLayout->addWidget(spin_min,3,2,1,1);

    QLabel* label_max = new QLabel("color bar high:");
    gridLayout->addWidget(label_max,4,0,1,2);
    gridLayout->addWidget(spin_max,4,2,1,1);

    QFrame *line_2 = new QFrame();
    line_2->setFrameShape(QFrame::HLine);
    line_2->setFrameShadow(QFrame::Sunken);
    gridLayout->addWidget(line_2,5,0,1,3);
    QLabel* label_color = new QLabel("special color");
    QLabel* label_val = new QLabel("value");
    gridLayout->addWidget(label_color,6,0,1,2);
    gridLayout->addWidget(label_val,6,2,1,1);
    gridLayout->addWidget(check_black,7,0,1,2);
    gridLayout->addWidget(spin_black,7,2,1,1);
    gridLayout->addWidget(check_white,8,0,1,2);
    gridLayout->addWidget(spin_white,8,2,1,1);
    gridLayout->addWidget(check_meg,9,0,1,2);
    gridLayout->addWidget(spin_meg,9,2,1,1);

    QFrame *line_3 = new QFrame();
    line_3->setFrameShape(QFrame::HLine);
    line_3->setFrameShadow(QFrame::Sunken);
    gridLayout->addWidget(line_3,13,0,1,3);
    gridLayout->addWidget(btn_update,14,2,1,1);
    gridLayout->addWidget(btn_reset,15,2,1,1);
    gridLayout->addWidget(btn_quit,16,2,1,1);

    setLayout(gridLayout);

    set_black();
    set_white();
    set_magenta();
    set_span();
    set_colormap();
}
Esempio n. 17
0
void lookPanel::_slot_sync_onetime()
{
    v3dhandleList win_list = m_v3d.getImageWindowList();
    int i1 = combo_master->currentIndex();
    int i2 = combo_slave->currentIndex();

    if (i1==i2)
    {
        v3d_msg("You have selected the same image. You need to specify and sync two different images. Try again!");
        return;
    }

    if (i1 <  win_list.size() &&
            i2 < win_list.size() &&
            i1 < win_list_past.size() &&
            i2  < win_list_past.size())
    {
        QString current1 = m_v3d.getImageName(win_list[i1]);
        QString current2 = m_v3d.getImageName(win_list[i2]);
        QString past1 = m_v3d.getImageName(win_list_past[i1]);
        QString past2 = m_v3d.getImageName(win_list_past[i2]);
        if (current1==past1  && current2==past2)
        {
            if (win_list[i1] && win_list[i2])//ensure the 3d viewer window is open; if not, then open it
            {
                m_v3d.open3DWindow(win_list[i1]);
                View3DControl *view_master = m_v3d.getView3DControl(win_list[i1]);
                m_v3d.open3DWindow(win_list[i2]);
                View3DControl *view_slave = m_v3d.getView3DControl(win_list[i2]);
                if (view_master && view_slave)
                {
                    view_master->absoluteRotPose();
                    int xRot = view_master->xRot();
                    int yRot = view_master->yRot();
                    int zRot = view_master->zRot();

                    int xShift = view_master->xShift();
                    int yShift = view_master->yShift();
                    int zShift = view_master->zShift();

                    int zoom = view_master->zoom();

                    if (check_rotation->isChecked())
                    {
                        view_slave->resetRotation();
                        view_slave->doAbsoluteRot(xRot,yRot,zRot);
                    }
                    if (check_shift->isChecked())
                    {
                        view_slave->setXShift(xShift);
                        view_slave->setYShift(yShift);
                        view_slave->setZShift(zShift);
                    }
                    if (check_zoom->isChecked())
                        view_slave->setZoom(zoom);
                }
            }
        }
        else
        {
            v3d_msg(warning_msg);
            QStringList items;
            for (int i=0; i<win_list.size(); i++)
                items << m_v3d.getImageName(win_list[i]);
            combo_master->clear(); combo_master->addItems(items);
            combo_slave->clear(); combo_slave->addItems(items);
            win_list_past = win_list;
            return;

        }
    }
    else
    {
        v3d_msg(warning_msg);
        QStringList items;
        for (int i=0; i<win_list.size(); i++)
            items << m_v3d.getImageName(win_list[i]);
        combo_master->clear(); combo_master->addItems(items);
        combo_slave->clear(); combo_slave->addItems(items);
        win_list_past = win_list;
        return;
    }
    return;
}
Esempio n. 18
0
void Image4DSimple::loadImage(const char* filename, bool b_useMyLib)
{
	cleanExistData(); // note that this variable must be initialized as NULL.

	strcpy(imgSrcFile, filename);

	V3DLONG * tmp_sz = 0; // note that this variable must be initialized as NULL.
	int tmp_datatype = 0;
	int pixelnbits=1; //100817

    const char * curFileSuffix = getSuffix(imgSrcFile);
    printf("The current input file has the suffix [%s]\n", curFileSuffix);

    if (curFileSuffix && (strcasecmp(curFileSuffix, "tif")==0 || strcasecmp(curFileSuffix, "tiff")==0 ||
        strcasecmp(curFileSuffix, "lsm")==0) ) //read tiff/lsm stacks
	{
            printf("Image4DSimple::loadImage loading filename=[%s]\n", filename);

#if defined _WIN32
		{
			v3d_msg("(Win32) Now try to use LIBTIFF (slightly revised by PHC) to read the TIFF/LSM...\n",0);
            if (strcasecmp(curFileSuffix, "tif")==0 || strcasecmp(curFileSuffix, "tiff")==0)
			{
				if (loadTif2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
				{
					v3d_msg("Error happens in TIF file reading (using libtiff). \n", false);
					b_error=1;
				}
			}
            else //if ( strcasecmp(curFileSuffix, "lsm")==0 ) //read lsm stacks
			{
				if (loadLsm2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
				{
					v3d_msg("Error happens in LSM file reading (using libtiff, slightly revised by PHC). \n", false);
					b_error=1;
				}
			}
		}

#else
		if (b_useMyLib)
		{
			v3d_msg("Now try to use MYLIB to read the TIFF/LSM again...\n",0);
			if (loadTif2StackMylib(imgSrcFile, data1d, tmp_sz, tmp_datatype, pixelnbits))
			{
				v3d_msg("Error happens in TIF/LSM file reading (using MYLIB). Stop. \n", false);
				b_error=1;
				return;
			}
			else
				b_error=0; //when succeed then reset b_error
		}
		else
		{
			v3d_msg("Now try to use LIBTIFF (slightly revised by PHC) to read the TIFF/LSM...\n",0);
            if (strcasecmp(curFileSuffix, "tif")==0 || strcasecmp(curFileSuffix, "tiff")==0)
			{
				if (loadTif2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
				{
					v3d_msg("Error happens in TIF file reading (using libtiff). \n", false);
					b_error=1;
				}
			}
            else //if ( strcasecmp(curFileSuffix, "lsm")==0 ) //read lsm stacks
			{
				if (loadLsm2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
				{
					v3d_msg("Error happens in LSM file reading (using libtiff, slightly revised by PHC). \n", false);
					b_error=1;
				}
			}
		}
                printf("Image4DSimple::loadImage finished\n");

#endif

	}    

    else if (curFileSuffix && (strcasecmp(curFileSuffix, "nrrd")==0 || strcasecmp(curFileSuffix, "nhdr")==0)) //read nrrd stacks
    {
        printf("Image4DSimple::loadImage loading filename=[%s]\n", filename);
        float pxinfo[4];
        float spaceorigin[3];
        if (!read_nrrd_with_pxinfo(imgSrcFile, data1d, tmp_sz, tmp_datatype, pxinfo, spaceorigin))
        {
            v3d_msg("Error happens in NRRD file reading. Stop. \n", false);
            b_error=1;
            return;
        }
        else
        {   //copy the pixel size and origin info when the nrrd read is successful
            //note that pixinfo[3] is reserved for future extension to include the temporal sampling rate. It is not used right now.
            rez_x = pxinfo[0];
            rez_y = pxinfo[1];
            rez_z = pxinfo[2];
            
            origin_x = spaceorigin[0];
            origin_y = spaceorigin[1];
            origin_z = spaceorigin[2];
        }
    }

    else if ( curFileSuffix && strcasecmp(curFileSuffix, "mrc")==0 ) //read mrc stacks
	{
		if (loadMRC2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
		{
			v3d_msg("Error happens in MRC file reading. Stop. \n", false);
			b_error=1;
			return;
		}
	}
#ifdef _ALLOW_WORKMODE_MENU_
    //else if ( curFileSuffix && ImageLoader::hasPbdExtension(QString(filename)) ) // read v3dpbd - pack-bit-difference encoding for sparse stacks
    else if ( curFileSuffix && strcasecmp(curFileSuffix, "v3dpbd")==0 ) // read v3dpbd - pack-bit-difference encoding for sparse stacks
    {
    	  v3d_msg("start to try v3dpbd", 0);
        ImageLoaderBasic imageLoader;
        if (! imageLoader.loadRaw2StackPBD(imgSrcFile, this, false) == 0) {
            v3d_msg("Error happens in v3dpbd file reading. Stop. \n", false);
            b_error=1;
            return;
        }
        // The following few lines are to avoid disturbing the existing code below
        tmp_datatype=this->getDatatype();
        tmp_sz=new V3DLONG[4];
        tmp_sz[0]=this->getXDim();
        tmp_sz[1]=this->getYDim();
        tmp_sz[2]=this->getZDim();
        tmp_sz[3]=this->getCDim();

        this->setFileName(filename); // PHC added 20121213 to fix a bug in the PDB reading.
    }
#endif
	else //then assume it is Hanchuan's Vaa3D RAW format
	{
		v3d_msg("The data does not have supported image file suffix, -- now this program assumes it is Vaa3D's RAW format and tries to load it... \n", false);
		if (loadRaw2Stack(imgSrcFile, data1d, tmp_sz, tmp_datatype))
		{
			printf("The data doesn't look like a correct 4-byte-size Vaa3D's RAW file. Try 2-byte-raw. \n");
			if (loadRaw2Stack_2byte(imgSrcFile, data1d, tmp_sz, tmp_datatype))
			{
				v3d_msg("Error happens in reading 4-byte-size and 2-byte-size Vaa3D's RAW file. Stop. \n", false);
				b_error=1;
				return;
			}
		}
	}

	//080302: now convert any 16 bit or float data to the range of 0-255 (i.e. 8bit)
	switch (tmp_datatype)
	{
		case 1:
			datatype = V3D_UINT8;
			break;

		case 2: //080824
			//convert_data_to_8bit((void *&)data1d, tmp_sz, tmp_datatype);
			//datatype = UINT8; //UINT16;
			datatype = V3D_UINT16;
			break;

		case 4:
			//convert_data_to_8bit((void *&)data1d, tmp_sz, tmp_datatype);
			datatype = V3D_FLOAT32; //FLOAT32;
			break;

		default:
			v3d_msg("The data type is not UINT8, UINT16 or FLOAT32. Something wrong with the program, -- should NOT display this message at all. Check your program. \n");
			if (tmp_sz) {delete []tmp_sz; tmp_sz=0;}
			return;
	}

	sz0 = tmp_sz[0];
	sz1 = tmp_sz[1];
	sz2 = tmp_sz[2];
	sz3 = tmp_sz[3]; //no longer merge the 3rd and 4th dimensions

	/* clean all workspace variables */

	if (tmp_sz) {delete []tmp_sz; tmp_sz=0;}

	return;
}
Esempio n. 19
0
void ImageTip::Compute_DFS()
{
	static int nDx[] = {-1,0,1,-1,0,1,-1,0,1};
	static int nDy[] = {-1,-1,-1,0,0,0,1,1,1};
	static int nDz[] = {-1,0,1};
	
	V3DLONG x = 0;
	V3DLONG y = 0;
	V3DLONG z = 0;
	V3DLONG count = 0;
	
	V3DLONG i = 0;
	V3DLONG j = 0;
	V3DLONG k = 0;
	V3DLONG l = 0;
	deque<DPoint_t> dfs;
	
	V3DLONG temp_l = 0;
	V3DLONG index_nei = 0;
	
    DPoint_t point;
	point.m_x = m_sptSeed.m_x + 1;
	point.m_y = m_sptSeed.m_y + 1;
	point.m_z = m_sptSeed.m_z + 1;
	point.m_l = 0;  
	dfs.push_back(point);
	
	try  //m_piDFS indicates the distance values
	{
		m_piDFS = new float [totallen]; 
	}
	catch (...)
	{
		v3d_msg("Fail to allocate memory in Distance Transform.", 0);
		if (m_piDFS) {delete []m_piDFS; m_piDFS=0;}
		return;
	}
	memset(m_piDFS, NONVISITED, totallen * sizeof(float));
	
	V3DLONG m_pagesz = realszx*realszy; 
	
	m_piDFS[point.m_z * m_pagesz + point.m_y * realszx + point.m_x] = 0; //the distance to the starting pt is 0 (of course!)
	
	while(!dfs.empty())
	{	
        point = dfs.front();
		dfs.pop_front();
		i = point.m_z;
		j = point.m_y;
		k = point.m_x;
		l = point.m_l;

		// 26
		count = 0; //to indicate the direction type
		for(int m = 0; m < 3; m++)
		{
			for(int n = 0; n < 9; n++)
			{
				z = i + nDz[m];
				y = j + nDy[n];
				x = k + nDx[n];
				++count;
				
				index_nei = z * m_pagesz + y * realszx + x;
				
				if (m_ppsImgData[index_nei] != BACKGROUND)
				{
					switch(count)
					{
						// 6 faces
						case 5:
						case 11:
						case 13:
						case 15:
						case 17:
						case 23:
							temp_l = l + 1;
							if(m_piDFS[index_nei] != NONVISITED)
							{
								if(temp_l < m_piDFS[index_nei])
								{
									//printf("temp=%d m_pidfs=%d\n",temp_l,m_piDFS[index_nei]);
									m_piDFS[index_nei] = temp_l;	
									point.m_x = x;
									point.m_y = y;
									point.m_z = z;
									point.m_l = temp_l;
									dfs.push_back(point);
								}
							}
							else //set initial value
							{
								//	printf("tem=%d",temp_l);
								m_piDFS[index_nei] = temp_l;	
								point.m_x = x;
								point.m_y = y;
								point.m_z = z;
								point.m_l = temp_l;
								dfs.push_back(point);
							}
							break;
							
						// 12 edges
						case 2:
						case 4:
						case 6:
						case 8:
						case 10:
						case 12:
						case 16:
						case 18:
						case 20:
						case 22:
						case 24:
						case 26:				
							temp_l = l + sqrt(2.0);
							if(m_piDFS[index_nei] != NONVISITED)
							{
								if(temp_l < m_piDFS[index_nei])
								{
									m_piDFS[index_nei] = temp_l;	
									point.m_x = x;
									point.m_y = y;
									point.m_z = z;
									point.m_l = temp_l;
									dfs.push_back(point);
								}
							}
							else //set initial value
							{
								m_piDFS[index_nei] = temp_l;	
								point.m_x = x;
								point.m_y = y;
								point.m_z = z;
								point.m_l = temp_l;
								dfs.push_back(point);
							}
							break;
							
						// 8 vertexes
						case 1:
						case 3:
						case 7:
						case 9:
						case 19:
						case 21:
						case 25:
						case 27:
							temp_l = l + sqrt(3.0);
							if(m_piDFS[index_nei] != NONVISITED)
							{
								if(temp_l < m_piDFS[index_nei])
								{
									m_piDFS[index_nei] = temp_l;	
									point.m_x = x;
									point.m_y = y;
									point.m_z = z;
									point.m_l = temp_l;
									dfs.push_back(point);
								}
							}
							else  //set initial value
							{
								m_piDFS[index_nei] = temp_l;	
								point.m_x = x;
								point.m_y = y;
								point.m_z = z;
								point.m_l = temp_l;
								dfs.push_back(point);
							}
							break;
						default:
							break;
					}
				}
			}
		}
	}
	
	return;
}
Esempio n. 20
0
void lookPanel::_slot_syncAuto()
{
    v3dhandleList win_list = m_v3d.getImageWindowList();

    bool b_filelistchanged = (win_list.size()==win_list_past.size()) ? false : true;
    if (!b_filelistchanged)
    {
        for (int i=0; i<win_list.size(); i++)
        {
            if (win_list.at(i) != win_list_past.at(i))
            {
                b_filelistchanged = true;
                break;
            }
        }
    }
    if (b_filelistchanged)
    {
        v3d_msg(warning_msg);
        QStringList items;
        for (int i=0; i<win_list.size(); i++)
            items << m_v3d.getImageName(win_list[i]);
        combo_master->clear(); combo_master->addItems(items);
        combo_slave->clear(); combo_slave->addItems(items);
        win_list_past = win_list;

        return;
    }

    //only execute the sync if the file list has not changed

    int i_master = combo_master->currentIndex();
    int i_slave = combo_slave->currentIndex();
    if (i_master==i_slave)
    {
        v3d_msg("You have selected the same image. You need to specify and sync two different images. Try again!");
        resetSyncAutoState();

        QStringList items;
        for (int i=0; i<win_list.size(); i++)
            items << m_v3d.getImageName(win_list[i]);
        if (combo_master)
        {
            combo_master->clear(); combo_master->addItems(items);
            combo_master->setEnabled(true);
        }

        if (combo_slave)
        {
            combo_slave->clear(); combo_slave->addItems(items);
            combo_slave->setEnabled(true);
        }

        return;
    }

    b_autoON = !b_autoON; // a simple bi-state switch

    if (b_autoON)
    {
        syncAuto->setText("Stop Sync (real time)");
        xRot_past = -1;
        yRot_past = -1;
        zRot_past = -1;
        xShift_past = -1;
        yShift_past = -1;
        zShift_past = -1;
        zoom_past = -1;

        if (!(view_master = m_v3d.getView3DControl(win_list[i_master])))
        {
            m_v3d.open3DWindow(win_list[i_master]);
            view_master = m_v3d.getView3DControl(win_list[i_master]);
        }

        if (!(view_slave = m_v3d.getView3DControl(win_list[i_slave])))
        {
            m_v3d.open3DWindow(win_list[i_slave]);
            view_slave = m_v3d.getView3DControl(win_list[i_slave]);
        }

        combo_master->setEnabled( false );
        combo_slave->setEnabled( false );

        long interval = 0.2 * 1000;
        m_pTimer->start(interval);
    }
    else
    {
        resetSyncAutoState();
        return;
    }
    return;
}
Esempio n. 21
0
bool join_two_V_NeuronSWC(V_NeuronSWC & destination_swc, V_NeuronSWC & subject_swc)
{
    if (subject_swc.nrows()<=0) {
        qDebug("subject_swc is empty in join_two_V_NeuronSWC()");
        return false;
    }
    if (destination_swc.nrows()<=0) {
        destination_swc = subject_swc;
        return true;
    }

    //step 0: to simplify the des neuron, to make the joining simpler
    if (!simplify_V_NeuronSWC_nodeindex(destination_swc))
    {
        qDebug("inconsistent destination neuron structure found in join_two_V_NeuronSWC()");
        return false; //some error happens
    }

    //first just concatenate records
    V_NeuronSWC_unit v, vp;
    V3DLONG i=0, j=0;

    V3DLONG nr_des = destination_swc.nrows();
    for (i=0; i<subject_swc.nrows(); i++)
    {
        v = subject_swc.row.at(i);
        v.n += nr_des;
        if (v.parent>=0) v.parent += nr_des;
        destination_swc.append(v);
    }
    nr_des = destination_swc.nrows();

    //then produce the adjacency matrix
    vector<V_NeuronSWC_coord> unpos = destination_swc.unique_ncoord();
    V3DLONG N = unpos.size();

    map <V3DLONG, V3DLONG> nid_row_lut;
    for (i=0; i<nr_des; i++) {
        nid_row_lut[destination_swc.row.at(i).n] = i;
    }

    map <V3DLONG, V3DLONG> row_unid_lut;
    for (i=0; i<nr_des; i++)
    {
        V_NeuronSWC_coord c = destination_swc.row.at(i).get_coord();
        V3DLONG ic = value_in_vector(unpos, c);
        if (ic<0)
        {
            v3d_msg("Indexing error! Check data in join_two_V_NeuronSWC.");
            return false;
        }
        row_unid_lut[i] = ic;
    }

    vector < vector <V3DLONG> > adjm;
    vector <V3DLONG> plist;
    for (i=0; i<N; i++) adjm.push_back(plist); //initialize as empty

    vector < vector <float> > adjm_radius;
    vector <float> tmpr;
    for (i=0; i<N; i++) adjm_radius.push_back(tmpr); //initialize as empty

    vector < vector <float> > adjm_type;
    vector <float> tmpt;
    for (i=0; i<N; i++) adjm_type.push_back(tmpt); //initialize as empty

    for (i=0; i<nr_des; i++)
    {
        v = destination_swc.row.at(i);
        V3DLONG iv = row_unid_lut[i];

        if (v.parent>=0)
        {
            vp = destination_swc.row.at(nid_row_lut[v.parent]);
            V3DLONG ip =  row_unid_lut[nid_row_lut[v.parent]];
            adjm.at(iv).push_back(ip); //add it anyway, will find unique one later. Indeed even unnecessary to find the unique ones, because the repeated record will merge automatically
            adjm_radius.at(iv).push_back(float(v.r));
            adjm_type.at(iv).push_back(float(v.type));
            //need to record neuron edge type and radius as well later
        }
        else
        {
            //do nothing about the parent, i.e. this is a root for this record, and thus do not add to the parent list at all
            //but still update type and radius
            adjm_radius.at(iv).push_back(float(v.r));
            adjm_type.at(iv).push_back(float(v.type));
        }
    }

    //no need to find unique ones

    //then re-produce a new swc
    V_NeuronSWC newswc = destination_swc;
    newswc.row.clear();
    for (i=0; i<N; i++)
    {
        vector <V3DLONG> & cur_pa = adjm.at(i);
        vector <float> & cur_r = adjm_radius.at(i);
        vector <float> & cur_t = adjm_type.at(i);
        V_NeuronSWC_coord & cur_coord = unpos.at(i);

        if (cur_pa.size()<=0) //a root
        {
            v.n = i;
            v.type = double(cur_t.back()); //direct use the last one, which means the later one overwrite the first one
            v.x = cur_coord.x;
            v.y = cur_coord.y;
            v.z = cur_coord.z;
            v.r = cur_r.back(); //direct use the last one, which means the later one overwrite the first one
            v.parent = -1;
            newswc.append(v);
        }
        else
        {
            for (j=0; j<cur_pa.size(); j++)
            {
                v.n = i;
                v.type = double(cur_t.at(j)); //allow he later one overwrite the earlier one(s) if there are redundant records
                v.x = cur_coord.x;
                v.y = cur_coord.y;
                v.z = cur_coord.z;
                v.r = cur_r.at(j); //so I allow the later one overwrite the earlier one(s) if there are redundant records
                v.parent = cur_pa.at(j);
                newswc.append(v);
            }
        }
    }


    //copy the results
    destination_swc = newswc;
    destination_swc.b_jointed = true;
    return true;
}
Esempio n. 22
0
bool combiner::eswc_generate()
{
    //qDebug()<<"in eswc generate";
    //1-5 spine. 1:volume; 2:max_dis; 3:min_dis; 4:center_dis; 5:head-width
    //6-7 IS. 6:volume; 2:on_dendrite

    for (QMap<int,node_info>::iterator iter_map=nodegroup_map.begin();
         iter_map!=nodegroup_map.end();iter_map++)
    {
//        qDebug()<<"key:"<<iter_map.key()<<" spine:"<<iter_map.value().spine_lut.size()<<
//                  " IS:"<<iter_map.value().is_lut.size();
        int node_id = iter_map.key();
        QVector<spineunit> spine_vec = iter_map.value().spine_lut;
        QVector<isunit> is_vec = iter_map.value().is_lut;

        //qDebug()<<"key:"<<iter_map.key()<<"spine:"<<spine_vec.size()<<" is:"<<is_vec.size();

        //needs to first check if the node_id goes beyond the swc
        //if true, then the swc and the table is not the right match
        if (node_id>neuron.listNeuron.size())
        {
            v3d_msg("SWC and tables do not match. Please check inputs.\n");
            return false;
        }

        //fill in the original node
        if (!spine_vec.isEmpty())
        {
            //take out the first spine
            spineunit first_spine = spine_vec.front();
            neuron.listNeuron[node_id].fea_val[0] = (float)first_spine.volume;
            neuron.listNeuron[node_id].fea_val[1] = (float)first_spine.max_dis;
            neuron.listNeuron[node_id].fea_val[2] = (float)first_spine.min_dis;
            neuron.listNeuron[node_id].fea_val[3] = (float)first_spine.center_dis;
            neuron.listNeuron[node_id].fea_val[4] = (float)first_spine.head_width;
            //pop out this spine
            spine_vec.pop_front();
        }
        if (!is_vec.isEmpty())
        {
            isunit first_is = is_vec.front();
            neuron.listNeuron[node_id].fea_val[5] = first_is.volume;
            neuron.listNeuron[node_id].fea_val[6] = first_is.on_dendrite;
            is_vec.pop_front();
        }
        //start creating new nodes
        while (!(is_vec.isEmpty() && spine_vec.isEmpty()))
        {
            NeuronSWC S;
            S.n = neuron.listNeuron.length()+1;
//            qDebug()<<"~~~~~~~~~~~~~New node add:"<<S.n<<"ori node: "<<neuron.listNeuron[node_id].n
//                   <<" ori node parent:"<<neuron.listNeuron[node_id].parent;
            S.type = neuron.listNeuron[node_id].type;
            S.x = neuron.listNeuron[node_id].x;
            S.y = neuron.listNeuron[node_id].y;
            S.z = neuron.listNeuron[node_id].z;
            S.r = neuron.listNeuron[node_id].r;
            S.parent = neuron.listNeuron[node_id].parent;
            S.fea_val.clear();
            for (int jj=0;jj<7;jj++)
                S.fea_val.push_back(-1);
            if (!spine_vec.isEmpty())
            {
                S.fea_val[0] = (float)spine_vec.front().volume;
                S.fea_val[1] = (float)spine_vec.front().max_dis;
                S.fea_val[2] = (float)spine_vec.front().min_dis;
                S.fea_val[3] = (float)spine_vec.front().center_dis;
                S.fea_val[4] = (float)spine_vec.front().head_width;
                spine_vec.pop_front();
            }
            if (!is_vec.isEmpty())
            {
                S.fea_val[5] = (float)is_vec.front().volume;
                S.fea_val[6] = (float)is_vec.front().on_dendrite;
                is_vec.pop_front();
            }
            neuron.listNeuron[node_id].parent=S.n;  //change the ori node's parent to this new node
            neuron.listNeuron.append(S);
        }
    }

    QString eswc_out_name="";
    if (!writeESWC_file(eswc_out_name,neuron))
        return false;
    //qDebug()<<"voxel_group:"<<neuron.listNeuron.size()<<"finish writing out"<<endl;
    QMessageBox::information(0,"combiner plug-in","File has been succesfully saved to the specified folder.",
                             QMessageBox::Ok);
    return true;
}
void pointcloud_atlas_builderPlugin::domenu(const QString &menu_name, V3DPluginCallback &callback, QWidget *parent)
{
    
    atlasConfig cfginfo;
    QDir curdir; 
    
//    v3d_msg(curdir.currentPath());
//    
//    printf("%s", curdir.currentPath().toStdString().c_str());

    QString fileName = curdir.currentPath() + V3DFOLDER;
      
	if (!loadPointCloudAtlasConfigFile(qPrintable(fileName.trimmed()), cfginfo))
	{
		v3d_msg("Fail to load the configuration file atlas_config.txt");
		return;
	}    
    
    
    
    if (menu_name == tr("Edit an existing point cloud atlas linker file"))
    {
		fl_procPC_Atlas_edit_atlaslinkerfile();
	}
	else if (menu_name == tr("Create a new point cloud atlas linker file"))
	{
		fl_procPC_Atlas_create_atlaslinkerfile();
	}
	else if (menu_name == tr("Build the atlas"))
	{
		fl_procPC_Atlas_build_atlas(cfginfo);
	}	
    else if (menu_name == tr("Detect coexpressing cells"))
    {
        fl_procPC_atlas_detect_coexpress_cells(cfginfo);
    }
//    else if (menu_name == tr("Edit coexpressing cells"))
//    {
//        fl_procPC_atlas_edit_coexpress_cells();
//    }
    else if (menu_name == tr("Merge coexpressing cells"))
    {
//        fl_procPC_atlas_merge_coexpress_cells(callback);
        fl_procPC_atlas_merge_coexpress_cells(cfginfo);
        
    }
//    else if (menu_name == tr("Display atlas"))
//    {
//        fl_procPC_atlas_display();
//    }    
    else if (menu_name == tr("Adjust preference"))
    {
        fl_procPC_adjust_preference();
    }
	else if (menu_name == tr("About this plugin"))
	{
		QMessageBox::information(parent, "Version info", "Point cloud atlas builder v1.0. Developed by Fuhui Long .");
	}
	else
		return;
}	
Esempio n. 24
0
bool doNeuronToolBoxPlugin(MainWindow* mainwindow, const vaa3d_neurontoolbox_paras & p)
{
	v3d_msg(QString("Now try to run NeuronToolbox [%1]").arg(p.OPS), 0);

	
	try 
	{
		QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
		if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
			pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
		if (pluginsDir.dirName() == "MacOS") {
			pluginsDir.cdUp();
			pluginsDir.cdUp();
			pluginsDir.cdUp();
		}
#endif
		if (pluginsDir.cd("plugins/neuron_toolbox")==false) 
		{
			v3d_msg("Cannot find ./plugins/neuron_toolbox directory!");
			return false;
		}
		
		QStringList fileList = pluginsDir.entryList(QDir::Files);
		if (fileList.size()<1)
		{
			v3d_msg("Cannot find any file in the ./plugins/neuron_toolbox directory!");
			return false;
		}
		
		QString fullpath = pluginsDir.absoluteFilePath(fileList.at(0)); //always just use the first file (assume it is the only one) found in the folder as the "correct" dll
    	QPluginLoader* loader = new QPluginLoader(fullpath);
        if (!loader)
        {
        	qDebug("unable to load neuron_toolbox plugin");
        	return false;
        }

//		v3d_msg(fullpath, 0);
		
	//	V3d_PluginLoader mypluginloader(mainwindow);
		V3d_PluginLoader* mypluginloader = mainwindow->pluginLoader;


		//mypluginloader.runPlugin(loader, QString("about this plugin"));

//		curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin
		
//		mypluginloader.runPlugin(loader, p.OPS);
		//mypluginloader.runPlugin(loader, "about");

		V3DPluginArgList input;
		V3DPluginArgList output;
		V3DPluginArgItem arg;
		arg.p = (void *)(&p);
		input<<arg;

		mypluginloader->callPluginFunc(fullpath, "neuron_toolbox", input, output);
	//	MainWindow * mainWin = qobject_cast<MainWindow*>(qApp->topLevelWidgets().at(0));	
		//mainwindow->pluginLoader->callPluginFunc(fullpath, "neuron_toolbox", input, output); 
			
	}
	catch (...)
	{
		v3d_msg("NeuronToolbox has a problem", 1);
		return false;
	}
	
	return true;
}
Esempio n. 25
0
bool eswc2swc_io(const V3DPluginArgList & input, V3DPluginArgList & output)
{
	cout<<"Welcome to eswc2swc_io"<<endl;
	
	vector<char*>* inlist = (vector<char*>*)(input.at(0).p);
	vector<char*>* outlist = NULL;

	if(input.size() != 1) 
	{
		printf("Please specify both input file name.\n");
		return false;
	}

	QString fileOpenName = QString(inlist->at(0));
	QString fileSaveName;
	QString tmp = fileOpenName;
	if (output.size()==0)
	{
		printf("No outputfile specified.\n");
		tmp.chop(4);
		fileSaveName = tmp + "swc";
	}
	else if (output.size()==1)
	{
		outlist = (vector<char*>*)(output.at(0).p);
		fileSaveName = QString(outlist->at(0));
	}
	else
	{
		printf("You have specified more than 1 output file.\n");
		return false;
	}

	NeuronTree neuron;
	vector<V3DLONG> segment_id, segment_layer;
	vector<double> feature;
	if (fileOpenName.endsWith(".eswc") || fileOpenName.endsWith(".ESWC"))
	{
		neuron = read_eswc(segment_id, segment_layer, feature, fileOpenName);
		if (!swc2eswc(neuron,segment_id, segment_layer))
		{
			v3d_msg("Cannot convert eswc to swc.\n");
			return false;
		}
	}
	else {
		v3d_msg("The file type you specified is not supported. Please check.");
		return false;
	}
	int ret = QMessageBox::Yes;
	if (check_eswc(neuron, segment_id, segment_layer)==-1)
	{
		v3d_msg("WARNING: Something is wrong with the eswc file", 0);
		v3d_msg("But we still put convert it to swc format", 0);
	}
	
	QString fileDefaultName = fileOpenName;
	fileDefaultName.chop(4);
	fileDefaultName += QString("swc");
	//write new SWC to file
	if (!export_swc(neuron,qPrintable(fileSaveName)))
	{
		v3d_msg("fail to write the output swc file.", 0);
		return false;
	}
	return true;
}
Esempio n. 26
0
void lookPanel::_slot_timerupdate()
{
    int i_master = combo_master->currentIndex();
    int i_slave = combo_slave->currentIndex();
    if (i_master==i_slave)
    {
        v3d_msg("Somehow you have specified the same image for both master and slave views. Do nothing!", 0);
        resetSyncAutoState();
        return;
    }

    if (!(view_master = m_v3d.getView3DControl(win_list[i_master])))
    {
        m_v3d.open3DWindow(win_list[i_master]);
        view_master = m_v3d.getView3DControl(win_list[i_master]);
    }

    if (!(view_slave = m_v3d.getView3DControl(win_list[i_slave])))
    {
        m_v3d.open3DWindow(win_list[i_slave]);
        view_slave = m_v3d.getView3DControl(win_list[i_slave]);
    }

    if (view_master && view_slave)
    {
        if (check_rotation->isChecked())
        {
            view_master->absoluteRotPose();
            int xRot = view_master->xRot();
            int yRot = view_master->yRot();
            int zRot = view_master->zRot();

            if (xRot!=xRot_past || yRot!=yRot_past || zRot!=zRot_past)
            {
                view_slave->resetRotation();
                view_slave->doAbsoluteRot(xRot,yRot,zRot);
                xRot_past = xRot;
                yRot_past = yRot;
                zRot_past = zRot;
            }
        }

        if (check_shift->isChecked())
        {
            int xShift = view_master->xShift();
            int yShift = view_master->yShift();
            int zShift = view_master->zShift();

            if (xShift!=xShift_past || yShift!=yShift_past || zShift!=zShift_past)
            {
                view_slave->setXShift(xShift);
                view_slave->setYShift(yShift);
                view_slave->setZShift(zShift);
                xShift_past = xShift;
                yShift_past = yShift;
                zShift_past = zShift;
            }
        }

        if (check_zoom->isChecked())
        {
            int zoom = view_master->zoom();
            if (zoom!=zoom_past)
            {
                view_slave->setZoom(zoom);
                zoom_past = zoom;
            }
        }
    }
}
Esempio n. 27
0
bool    SortESWC(QList<NeuronSWC> & neurons, QList<NeuronSWC> & result, V3DLONG newrootid, double thres)
{
    if (neurons.size()<1){
        cout <<"sorteswc(): empty input neuron."<<endl;
        return false;
    }



    //create a LUT, from the original id to the position in the listNeuron, different neurons with the same x,y,z & r are merged into one position
    QHash<V3DLONG, V3DLONG> LUT = getUniqueLUT(neurons);

    //create a new id list to give every different neuron a new id
    QList<V3DLONG> idlist = ((QSet<V3DLONG>)LUT.values().toSet()).toList();

    //create a child-parent table, both child and parent id refers to the index of idlist
    QHash<V3DLONG, V3DLONG> cp = ChildParent(neurons,idlist,LUT);


    V3DLONG siz = idlist.size();

    bool** matrix = new bool*[siz];
    for (V3DLONG i = 0;i<siz;i++)
    {
        matrix[i] = new bool[siz];
        for (V3DLONG j = 0;j<siz;j++) matrix[i][j] = false;
    }


    //generate the adjacent matrix for undirected matrix
    for (V3DLONG i = 0;i<siz;i++)
    {
        QList<V3DLONG> parentSet = cp.values(i); //id of the ith node's parents
        for (V3DLONG j=0;j<parentSet.size();j++)
        {
            V3DLONG v2 = (V3DLONG) (parentSet.at(j));
            if (v2==-1) continue;
            matrix[i][v2] = true;
            matrix[v2][i] = true;
        }
    }


    //do a DFS for the the matrix and re-allocate ids for all the nodes
    V3DLONG root = idlist.indexOf(LUT.value(1)); //default value: the first node, in case there is no root defined in the input swc
    if (newrootid==VOID)
    {
        for (V3DLONG i=0;i<neurons.size();i++)
            if (neurons.at(i).pn==-1){
                root = idlist.indexOf(LUT.value(neurons.at(i).n));
                break;
            }
    }
    else{
        root = idlist.indexOf(LUT.value(newrootid));

        if (LUT.keys().indexOf(newrootid)==-1)
        {
            v3d_msg("The new root id you have chosen does not exist in the SWC file.");
            return(false);
        }
    }

    V3DLONG* neworder = new V3DLONG[siz];
    int* numbered = new int[siz];
    for (V3DLONG i=0;i<siz;i++) numbered[i] = 0;

    V3DLONG id[] = {0};

    int group[] = {1};
    DFS(matrix,neworder,root,id,siz,numbered,group);

    while (*id<siz)
    {
        V3DLONG iter;
        (*group)++;
        for (iter=0;iter<siz;iter++)
            if (numbered[iter]==0) break;
        DFS(matrix,neworder,iter,id,siz,numbered,group);
    }


    //find the point in non-group 1 that is nearest to group 1,
    //include the nearest point as well as its neighbors into group 1, until all the nodes are connected
    while((*group)>1)
    {
        double min = VOID;
        double dist2 = 0;
        int mingroup = 1;
        V3DLONG m1,m2;
        for (V3DLONG ii=0;ii<siz;ii++){
            if (numbered[ii]==1)
                for (V3DLONG jj=0;jj<siz;jj++)
                    if (numbered[jj]!=1)
                    {
                        dist2 = computeDist2(neurons.at(idlist.at(ii)),neurons.at(idlist.at(jj)));
                        if (dist2<min)
                        {
                            min = dist2;
                            mingroup = numbered[jj];
                            m1 = ii;
                            m2 = jj;
                        }
                    }
        }
        for (V3DLONG i=0;i<siz;i++)
            if (numbered[i]==mingroup)
                numbered[i] = 1;
        if (min<=thres*thres)
        {
            matrix[m1][m2] = true;
            matrix[m2][m1] = true;
        }
        (*group)--;
    }

    id[0] = 0;
    for (int i=0;i<siz;i++)
    {
        numbered[i] = 0;
        neworder[i]= VOID;
    }

    *group = 1;

    V3DLONG new_root=root;
    V3DLONG offset=0;
    while (*id<siz)
    {
        V3DLONG cnt = 0;
        DFS(matrix,neworder,new_root,id,siz,numbered,group);
        (*group)++;
        NeuronSWC S;
        S.n = offset+1;
        S.pn = -1;
        V3DLONG oripos = idlist.at(new_root);
        S.x = neurons.at(oripos).x;
        S.y = neurons.at(oripos).y;
        S.z = neurons.at(oripos).z;
        S.r = neurons.at(oripos).r;
        S.type = neurons.at(oripos).type;
        S.seg_id = neurons.at(oripos).seg_id;
        S.level = neurons.at(oripos).level;
        S.fea_val = neurons.at(oripos).fea_val;


        result.append(S);
        cnt++;

        for (V3DLONG ii=offset+1;ii<(*id);ii++)
        {
            for (V3DLONG jj=offset;jj<ii;jj++) //after DFS the id of parent must be less than child's
            {
                if (neworder[ii]!=VOID && neworder[jj]!=VOID && matrix[neworder[ii]][neworder[jj]] )
                {
                        NeuronSWC S;
                        S.n = ii+1;
                        S.pn = jj+1;
                        V3DLONG oripos = idlist.at(neworder[ii]);
                        S.x = neurons.at(oripos).x;
                        S.y = neurons.at(oripos).y;
                        S.z = neurons.at(oripos).z;
                        S.r = neurons.at(oripos).r;
                        S.type = neurons.at(oripos).type;
                        S.seg_id = neurons.at(oripos).seg_id;
                        S.level = neurons.at(oripos).level;
                        S.fea_val = neurons.at(oripos).fea_val;
                        result.append(S);
                        cnt++;

                        break; //added by CHB to avoid problem caused by loops in swc, 20150313
                }
            }
        }
        for (new_root=0;new_root<siz;new_root++)
            if (numbered[new_root]==0) break;
        offset += cnt;
    }

    if ((*id)<siz) {
        v3d_msg("Error!");
        return false;
    }

    //free space by Yinan Wan 12-02-02
    if (neworder) {delete []neworder; neworder=NULL;}
    if (numbered) {delete []numbered; numbered=NULL;}
    if (matrix){
        for (V3DLONG i=0;i<siz;i++) {delete matrix[i]; matrix[i]=NULL;}
        if (matrix) {delete []matrix; matrix=NULL;}
    }


    return(true);
};
void fl_func_procIO_import_atlas_apofolder(apoAtlasLinkerInfoAll & apoinfo)
{
	//	QMessageBox::information(0, "Information about import pointcloud APO files to an .atlas linker file",
	//							 "To import a series of images to an .atlas linker file, these files should be put into the same folder and have the same size (X,Y,Z dimensions and number of color channels). <br><br>"
	//							 "You will be first asked to specify one of these files, and you can define a string filter of their file names.<br><br>"
	//							 "Normally these files should be aligned/registered images; but this function can also be used to produce a linker file just for screening a series of image stacks.<br><br>"
	//							 "Note that these files must be valid .tif files (or another image file format supported in V3D).<br><br>"
	//							 "You will be then asked to specify a file name of the output .atlas linker file.<br><br>"
	//							 );
	
	//first load a series of annotation files and build the record
	
	while (1)
	{
		PointCloudAtlas_LinkerLoadDialog d(apoinfo); //everytime create a new dialog instance, so that apoinfo becomes longer and longer
		int rescode = d.exec();
		
		if (rescode==QDialog::Accepted)
		{
			d.fetchData(apoinfo);
			printf("Now apoinfo has the %d classes\n", apoinfo.items.size());
			break;
		}
		else if (rescode==QDialog::Rejected)
		{
			v3d_msg("The point cloud atlas linker file editing is canceled.");
			return; //break;
		}
		else if (rescode==2) //"2" is a special code I define in dialog_pointcloudatlas_linkerload.cpp for "add another"
		{
			d.fetchData(apoinfo);
			printf("Now apoinfo has the %d classes\n", apoinfo.items.size());
		}
		else
		{
			v3d_msg("invalid rescode returned in PointCloudAtlas_LinkerLoadDialog(). Check your program.");
			break;
		}
	}
	
	//now determine the output .atlas file
	QString fileName = QFileDialog::getSaveFileName(0, QString("Save Atlas File (*.pc_atlas)"),
													"import.pc_atlas",
													QString("point cloud atlas linker file (*.pc_atlas)"));
    if (fileName.isEmpty())
	{
		v3d_msg("No output file is selected. Do nothing.");
		return;
	}

	
	
	//append(".pc_atlas");
		
	
	//now save the record to a pointcloud atlas file
	
	if (savePointCloudAtlasInfoListToFile(qPrintable(fileName), apoinfo))
		v3d_msg(qPrintable(fileName.prepend("The point cloud atlas linker file [").append("] has been created.")));
	else
		v3d_msg("Fail to save the point cloud atlas file.");
	
}
Esempio n. 29
0
bool join_two_V_NeuronSWC_old(V_NeuronSWC & destination_swc, V_NeuronSWC & subject_swc)
{
    if (subject_swc.nrows()<=0)
    {
        qDebug("subject_swc is empty in join_two_V_NeuronSWC()");
        return false;
    }

    if (destination_swc.nrows()<=0) {
        destination_swc = subject_swc;
        return true;
    }
    else
    {
        if (!simplify_V_NeuronSWC_nodeindex(destination_swc))
        {
            qDebug("inconsistent destination neuron structure found in join_two_V_NeuronSWC()");
            return false; //some error happens
        }

        V_NeuronSWC_unit v;
        V3DLONG i=0;
        destination_swc.printInfo();
        //one problem I don't consider now is that the nodes (3D locations) in a neuron reconstruction may duplicated. This should be simplified later too

        V3DLONG n0 = destination_swc.nrows();

        map <V3DLONG, V3DLONG> sub_index_map = unique_V_NeuronSWC_nodeindex(subject_swc);
        V3DLONG *ipos=0;
        ipos=new V3DLONG [subject_swc.nrows()];
        qDebug()<<"start ==================== map "<<subject_swc.name.c_str();
        for (i=0; i<subject_swc.nrows(); i++)
        {
            ipos[i] = destination_swc.getFirstIndexof3DPos(subject_swc.row.at(i));
            if (ipos[i]>=0) qDebug("**detect an overlapping node [sub ind = %d, dest_ind=%d]",i,ipos[i]);
            sub_index_map[subject_swc.row.at(i).data[0]] = (ipos[i]>=0) ? destination_swc.row.at(ipos[i]).data[0] : (sub_index_map[subject_swc.row.at(i).data[0]]+n0);
            qDebug()<<"map "<<subject_swc.row.at(i).data[0]<<" to "<<sub_index_map[subject_swc.row.at(i).data[0]];
        }
        qDebug()<<"finish ==================== map ";

        for (i=0; i<subject_swc.nrows(); i++)
        {
            v = subject_swc.row.at(i);
            qDebug()<<i<<"before : "<<v.data[0]<<" "<<v.data[1]<<" "<<v.data[2]<<" "<<v.data[3]<<" "<<v.data[4]<<" "<<v.data[5]<<" "<<v.data[6];

            v.data[0] = sub_index_map[v.data[0]];
            if (ipos[i]>=0) //overlap
            {
                if (v.data[6]>=0) //non-root
                {
                    if (ipos[V3DLONG(v.data[6])]<0) //if the parent overlap as well, then do no add
                    {
                        v.data[6] = sub_index_map[v.data[6]]; //if the overalp node is not a root (thus has its own parent, then inherit)
                        destination_swc.append(v); //in this case, still need to add this swc unit into the dest_swc
                    }
                }
                else //root
                {
                    v.data[6] = destination_swc.row.at(ipos[i]).data[6]; //if the overlap node is a root for subject seg, then copy the parent in dest_swc
                    qDebug()<<"**omit one overlap node **";
                    //in this case, no need to add this swc unit into the dest_swc
                }
            }
            else //if not an overlap node, should just add (but the node indexes should be updated)
            {
                if (v.data[6]>=0)
                {
                    v.data[6] = sub_index_map[v.data[6]]; //if the overalp node is not a root (thus has its own parent, then inherit)
                    destination_swc.append(v);
                }
                else
                {
                    //if the overlap node is a root for subject seg, then copy the parent in dest_swc
                    qDebug()<<"**copy a non-overlapping root node **";
                    destination_swc.append(v);	//in this case, still need to add as it is not overlap
                }
            }
            qDebug()<<i<<"after : "<<v.data[0]<<" "<<v.data[1]<<" "<<v.data[2]<<" "<<v.data[3]<<" "<<v.data[4]<<" "<<v.data[5]<<" "<<v.data[6];
        }

        //search for all root nodes
        destination_swc.printInfo();
        vector < vector<V3DLONG> > des_rootnode_overlap_info;
        vector <V3DLONG> overlap_root_array;
        V_NeuronSWC newswc = destination_swc;
        newswc.row.clear();
        for (i=0; i<destination_swc.row.size(); i++) //note that I search the entire merged destination, so that the part originally from subject will get searched again
        {
            v = destination_swc.row.at(i);
            if (v.parent<0)
            {
                vector <V3DLONG> mypos = destination_swc.getAllIndexof3DPos(v, i);
                if (mypos.size()>1)
                {
                    v3d_msg("Detect a root node that has the same coordinates of more than one other neuron nodes. Your data may have error. ");
                }

                if (mypos.size()>0) //overlap root, remove
                {
                    vector <V3DLONG> mypos1;
                    for (V3DLONG j=0; j<mypos.size(); j++)
                    {
                        if (destination_swc.row.at(mypos.at(j)).parent<0) //if it is a root
                        {
                            if (destination_swc.row.at(mypos.at(j)).n!=v.n) //then it is not a redundant row, -- maybe there is some other nodes link to this one. then do not add it to the newswc
                            {
                                destination_swc.row.at(mypos.at(j)).n = v.n;
                            }
                        }
                        else //the overlap one is not a root
                        {
                            if (destination_swc.row.at(mypos.at(j)).n!=v.n)
                                mypos1.push_back(destination_swc.row.at(mypos.at(j)).n);
                            //if equal, do nothing (which means remove this root-row. In this case, no node mapping is needed, but the root should be deleted
                        }
                    }

                    if (mypos1.size()>0)
                    {
                        overlap_root_array.push_back(v.n);
                        des_rootnode_overlap_info.push_back(mypos1);
                        //remove the current row by not copy to the new structure

                        qDebug()<<"remove overlap root node"<<v.n;
                    }
                    //newswc.append(v);
                }
                else //non-overlapping root, keep
                {
                    newswc.append(v);
                }
            }
            else //non_root, keep
            {
                newswc.append(v);
            }
        }

        for (i=0; i<overlap_root_array.size(); i++)
            qDebug()<<"overlapping root array "<<overlap_root_array.at(i);

        for (i=0; i<newswc.row.size(); i++) //now merge & update
        {
            v = newswc.row.at(i);
            V3DLONG cur_parent = V3DLONG(v.parent);
            V3DLONG mytmp = value_in_vector(overlap_root_array, cur_parent);
            if (mytmp>=0)
            {
                qDebug()<<"cur node "<<v.n<< " cur parent "<<v.parent << "new parent " << des_rootnode_overlap_info.at(mytmp).at(0);
                newswc.row.at(i).parent = des_rootnode_overlap_info.at(mytmp).at(0);

                for (V3DLONG j=1; j<des_rootnode_overlap_info.at(mytmp).size(); j++)
                {
                    v.parent = des_rootnode_overlap_info.at(mytmp).at(j);
                    newswc.append(v); //append some new records if one root mapped to multiple other non-root nodes
                }
            }
        }
        destination_swc = newswc; //update

        //save a temp swc file
        FILE * fp = fopen("/Users/pengh/temp/testaaa.swc", "wt");
        if (fp)
        {
            fprintf(fp, "#name %s\n", "test123.swc");
            fprintf(fp, "#comment %s\n", "jointed neuron");

            fprintf(fp, "#n,type,x,y,z,radius,parent\n");
            for (i=0; i<destination_swc.row.size(); i++)
            {
                v = destination_swc.row.at(i);
                fprintf(fp, "%ld %ld %5.3f %5.3f %5.3f %5.3f %ld\n", V3DLONG(v.data[0]), V3DLONG(v.data[1]), v.data[2], v.data[3], v.data[4], v.data[5], V3DLONG(v.data[6]));
            }

            fclose(fp);
        }

        if(ipos) {
            delete []ipos;
            ipos=0;
        }
    }

    destination_swc.b_jointed = true; //091029 RZC
    return true;
}
Esempio n. 30
0
bool ImageTip::Initialize(unsigned char* data, V3DLONG sz[3]) //do padding
{
	try
	{
		if (!data || !sz || sz[0]<=0 || sz[1]<=0 || sz[2]<=0)
		{
			v3d_msg("Invalid data in SetImageInfo()", 0);
			return false;
		}
	}
	catch (...)
	{
		v3d_msg("Invalid data in SetImageInfo()", 0);
		return false;
	}

	m_ppsOriData1D = data;
	m_szx = sz[0];
	m_szy = sz[1];
	m_szz = sz[2];

    // add margins to x,y,z for 26 neighborhood searching
	realszx = m_szx + 2;
	realszy = m_szy + 2;
	realszz = m_szz + 2;
	totallen = realszx*realszy*realszz;
	
	V3DLONG i,j,k;
	V3DLONG pagesz = realszx*realszy;
	
	//allocate memory and set default
	m_ppsImgData = new unsigned char [totallen];
	memset(m_ppsImgData, BACKGROUND, totallen);
	
	//padding with 1 (margin)
	for (k=0; k<m_szz; k++)
		for (j=0; j<m_szy; j++)
			for (i=0; i<m_szx; i++)
			{
				m_ppsImgData[(k+1)*pagesz + (j+1)*realszx + (i+1)] = m_ppsOriData1D[(k)*m_szy*m_szx + (j)*m_szx + (i)];
			}
	
	//find all boundary/surface points
	for (V3DLONG k=1; k<realszz-1; k++)
		for (V3DLONG j=1; j<realszy-1; j++)
			for (V3DLONG i=1; i<realszx-1; i++)
			{
				if (m_ppsImgData[k*pagesz + j*realszx + i] != BACKGROUND)
				{
					for (int koff=-1; koff<=1; koff++)
						for (int joff=-1; joff<=1; joff++)
							for (int ioff=-1; ioff<=1; ioff++)
								if (m_ppsImgData[(k+koff)*pagesz + (j+joff)*realszx + (i+ioff)] == BACKGROUND)
								{
									DPoint_t t;
									t.m_x = i; t.m_y = j; t.m_z = k; t.m_l = -1;
									m_vdfbptSurface.push_back(t);
									goto Label_BoundaryPt_Found;
								}
				}
				
			Label_BoundaryPt_Found:
				continue;
			}
	
	//
	return true;
}