Beispiel #1
0
bool userOutput(std::string id)
{
    if (id.length() == 0)
        return false;
    
    std::string xml = getImageInfo(id);
    
	if (optDirect)
		printf("%s\n", getVal(xml, "link").c_str());
	if (optImagePage)
		printf("http://imgur.com/%s\n", id.c_str());
	if (optHtmlImage)
		printf("<img src=\"%s\" alt=\"Hosted by imgur.com\" />\n", getVal(xml, "link").c_str());
	if (optHtmlLink)
		printf("<a href=\"%s\" title=\"Hosted by imgur.com\">%s</a>\n", getVal(xml, "link").c_str(), getVal(xml, "link").c_str());
	if (optMessageBoard)
		printf("[IMG]%s[/IMG]\n", getVal(xml, "link").c_str());
	if (optMessageBoardLink)
		printf("[URL=%s][IMG]%s[/IMG][/URL]\n", getVal(xml, "link").c_str(), getVal(xml, "link").c_str());
	if (optOpenBrowser)
    {
        std::string url = "http://imgur.com/" + id;
		browseTo(url);
    }
	
	return true;
}
bool checkImageFileSize(const FileName &name, bool error)
{
    ImageInfo imgInfo;
    getImageInfo(name, imgInfo);

    return checkImageFileSize(name, imgInfo, error);
}
Beispiel #3
0
bool userOutput(std::string id)
{
    if (id.length() == 0)
        return false;
    
    std::string xml = getImageInfo(id);
    std::string output;
    
	if (optDirect)
		spf(output, "%s\n", getVal(xml, "link").c_str());
	if (optImagePage)
		spf(output, "http://imgur.com/%s\n", id.c_str());
	if (optHtmlImage)
		spf(output, "<img src=\"%s\" alt=\"Hosted by imgur.com\" />\n", getVal(xml, "link").c_str());
	if (optHtmlLink)
		spf(output, "<a href=\"%s\" title=\"Hosted by imgur.com\">%s</a>\n", getVal(xml, "link").c_str(), getVal(xml, "link").c_str());
	if (optMessageBoard)
		spf(output, "[IMG]%s[/IMG]\n", getVal(xml, "link").c_str());
	if (optMessageBoardLink)
		spf(output, "[URL=%s][IMG]%s[/IMG][/URL]\n", getVal(xml, "link").c_str(), getVal(xml, "link").c_str());
	if (optOpenBrowser)
    {
        std::string url = "http://imgur.com/" + id;
		browseTo(url);
    }
    if (output.length() > 0)
        puts(output.c_str());
    if (optCopyClipboard && output.length() > 0)
        clipBuffer += output;
    
	return true;
}
Beispiel #4
0
DFNode *WordDrawingGet(WordGetData *get, DFNode *concrete)
{
    ImageInfo *info = getImageInfo(concrete);
    if (info == NULL)
        return createAbstractPlaceholder(get,"[Unsupported object]",concrete);

    int validFileType = 0;

    const char *filename = WordPackageTargetForDocumentRel(get->conv->package,info->rId);
    if (filename != NULL) {
        char *origExtension = DFPathExtension(filename);
        char *lowerExtension = DFLowerCase(origExtension);
        if (DFHashTableLookup(get->conv->supportedContentTypes,lowerExtension) != NULL)
            validFileType = 1;
        free(origExtension);
        free(lowerExtension);
    }

    DFNode *result = NULL;
    if (!validFileType) {
        if (info->progId != NULL) {
            char *message = DFFormatString("[Unsupported object: %s]",info->progId);
            DFNode *placeholder = createAbstractPlaceholder(get,message,concrete);
            free(message);
            result = placeholder;
        }
        else {
            result = createAbstractPlaceholder(get,"[Unsupported object]",concrete);
        }

    }

    if (result == NULL)
        result = imageWithFilename(get,filename,info->widthPts,concrete);

    ImageInfoFree(info);
    return result;
}
bool Images::makeThumb ( ) {
	// did it have an error?
	if ( g_errno ) {
		// just give up on all of them if one has an error
		log ( "image: had error downloading image on page %s: %s. "
		      "Not downloading any more.",
		      m_pageUrl->getUrl(),mstrerror(g_errno));
		// stop it
		m_stopDownloading = true;
		return true;
	}
	char *buf;
	long  bufLen, bufMaxLen;
	HttpMime mime;
	m_imgData     = NULL;
	m_imgDataSize = 0;

	log( LOG_DEBUG, "image: gotImage() entered." );
	// . if there was a problem, just ignore, don't let it stop getting
	//   the real page.
	if ( g_errno ) {
		log( "ERROR? g_errno puked: %s", mstrerror(g_errno) );
		//g_errno = 0;
		return true;
	}
	//if ( ! slot ) return true;
	// extract image data from the socket
	buf       = m_msg13.m_replyBuf;
	bufLen    = m_msg13.m_replyBufSize;
	bufMaxLen = m_msg13.m_replyBufAllocSize;
	// no image?
	if ( ! buf || bufLen <= 0 ) {
		g_errno = EBADIMG;
		return true;
	}
	// we are image candidate #i
	//long i = m_j - 1;
	// get img tag node
	// get the url of the image
	long  srcLen;
	char *src = NULL;
	if ( m_xd->m_isDiffbotJSONObject ) {
		src = *m_xd->getDiffbotPrimaryImageUrl();
		srcLen = gbstrlen(src);
	}
	else {
		long node = m_imageNodes[m_j];
		src = m_xml->getString(node,"src",&srcLen);
	}
	// set it to the full url
	Url iu;
	// use "pageUrl" as the baseUrl
	iu.set ( m_pageUrl , src , srcLen ); 
	// get the mime
	if ( ! mime.set ( buf, bufLen, &iu ) ) {		
		log ( "image: MIME.set() failed in gotImage()" );
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// set the status so caller can see
	long httpStatus = mime.getHttpStatus();
	// check the status
	if ( httpStatus != 200 ) {
		log( LOG_DEBUG, "image: http status of img download is %li.",
		     m_httpStatus);
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// make sure this is an image
	m_imgType = mime.getContentType();
	if ( m_imgType < CT_GIF || m_imgType > CT_TIFF ) {
		log( LOG_DEBUG, "image: gotImage() states that this image is "
		     "not in a format we currently handle." );
		// try the next image if any
		g_errno = EBADIMG;
		return true;
	}
	// get the content
	m_imgData     = buf + mime.getMimeLen();
	m_imgDataSize = bufLen - mime.getMimeLen();
	// Reset socket, so socket doesn't free the data, now we own
	// We must free the buf after thumbnail is inserted in TitleRec
	m_imgReply       = buf;//slot->m_readBuf;
	m_imgReplyLen    = bufLen;//slot->m_readBufSize;
	m_imgReplyMaxLen = bufMaxLen;//slot->m_readBufMaxSize;
	// do not let UdpServer free the reply, we own it now
	//slot->m_readBuf = NULL;

	if ( ! m_imgReply || m_imgReplyLen == 0 ) {
		log( LOG_DEBUG, "image: Returned empty image reply!" );
		g_errno = EBADIMG;
		return true;
	}

	// get next if too small
	if ( m_imgDataSize < 20 ) { g_errno = EBADIMG; return true; }

	long imageType;
	getImageInfo ( m_imgData, m_imgDataSize, &m_dx, &m_dy, &imageType );

	// log the image dimensions
	log( LOG_DEBUG,"image: Image Link: %s", iu.getUrl() );
	log( LOG_DEBUG,"image: Max Buffer Size: %lu bytes.",m_imgReplyMaxLen);
	log( LOG_DEBUG,"image: Image Original Size: %lu bytes.",m_imgReplyLen);
	log( LOG_DEBUG,"image: Image Buffer @ 0x%lx - 0x%lx",(long)m_imgReply, 
	     (long)m_imgReply+m_imgReplyMaxLen );
	log( LOG_DEBUG, "image: Size: %lupx x %lupx", m_dx, m_dy );

	// what is this?
	if ( m_dx <= 0 || m_dy <= 0 ) {
		log(LOG_DEBUG, "image: Image has bad dimensions.");
		g_errno = EBADIMG;
		return true;
	}


	// skip if bad dimensions
	if( ((m_dx < 50) || (m_dy < 50)) && ((m_dx > 0) && (m_dy > 0)) ) {
		log(LOG_DEBUG,
		    "image: Image is too small to represent a news article." );
		g_errno = EBADIMG;
		return true;
	}

	// skip if bad aspect ratio. 5x1 or 1x5 is bad i guess
	if ( m_dx > 0 && m_dy > 0 ) {
		float aspect = (float)m_dx / (float)m_dy;
		if ( aspect < .2 || aspect > 5.0 ) {
			log(LOG_DEBUG,
			    "image: Image aspect ratio is worse that 5 to 1");
			g_errno = EBADIMG;
			return true;
		}
	}


	// update status
	if ( m_xd ) m_xd->setStatus ( "making thumbnail" );
	// log it
	log ( LOG_DEBUG, "image: gotImage() thumbnailing image." );
	// create the thumbnail...
	// reset this... why?
	g_errno = 0;
	// reset this since filterStart_r() will set it on error
	m_errno = 0;
	// callThread returns true on success, in which case we block
	if ( g_threads.call ( FILTER_THREAD        ,
			      MAX_NICENESS         ,
			      this                 ,
			      makeThumbWrapper    ,
			      thumbStartWrapper_r ) ) return false;
	// threads might be off
	logf ( LOG_DEBUG, "image: Calling thumbnail gen without thread.");
	thumbStartWrapper_r ( this , NULL );
	return true;
}
    void ResStarlingAtlas::loadAtlas(CreateResourceContext& context)
    {
        std::string xml_path = context.walker.getPath("file");

        file::buffer fb;
        file::read(xml_path, fb);

        pugi::xml_document doc;
        doc.load_buffer_inplace(&fb.data[0], fb.data.size());

        pugi::xml_node starling_xml = doc.first_child();

        pugi::xml_node root = doc.root().first_child();
        const std::string& img = root.attribute("imagePath").as_string();

        char head[255];
        char tail[255];
        path::split(xml_path.c_str(), head, tail);
        _imagePath = std::string(head) + img;

        _texture = IVideoDriver::instance->createTexture();

        pugi::xml_node meta = context.walker.getMeta();

        if (!meta.empty())
        {
            int textureWidth = meta.attribute("tw").as_int();
            int textureHeight = meta.attribute("th").as_int();
            _texture->init(0, textureWidth, textureHeight, TF_R8G8B8A8);
        }
        else
        {

            unsigned char buff[64];
            unsigned int size = 0;
            {
                file::autoClose ac(file::open(_imagePath, "rb"));
                size = file::read(ac.getHandle(), buff, sizeof(buff));
            }

            int width = 0;
            int height = 0;
            ImageType type;

            if (getImageInfo(buff, size, img.c_str(), type, width, height))
            {
                _texture->init(0, width, height, TF_R8G8B8A8);
            }
            else
            {
                spMemoryTexture mt = new MemoryTexture;

                ImageData im;
                file::buffer bf;
                file::read(_imagePath, bf);

                mt->init(bf, true, _texture->getFormat());
                im = mt->lock();
                _texture->init(mt->lock(), false);
            }
        }


        float iw = 1.0f / _texture->getWidth();
        float ih = 1.0f / _texture->getHeight();

        ResAnim* resAnim = 0;
        pugi::xml_node sub = starling_xml.first_child();

        animationFrames frames;

        while (sub)
        {
            const char* name = sub.attribute("name").value();

            char id[255];
            strcpy(id, name);

            //int frame_index = atoi(index);

            //todo optimize attributes
            int x = sub.attribute("x").as_int();
            int y = sub.attribute("y").as_int();
            int width = sub.attribute("width").as_int();
            int height = sub.attribute("height").as_int();

            int frameX = sub.attribute("frameX").as_int();
            int frameY = sub.attribute("frameY").as_int();
            int frameWidth = sub.attribute("frameWidth").as_int(width);
            int frameHeight = sub.attribute("frameHeight").as_int(height);

            if (!resAnim || resAnim->getName() != id)
            {
                if (resAnim)
                {
                    resAnim->init(frames, (int)frames.size());
                    resAnim->setParent(this);
                    context.resources->add(resAnim);
                    frames.clear();
                }

                resAnim = new ResAnim(this);
                setNode(resAnim, context.walker.getNode());
                resAnim->setName(id);
            }

            AnimationFrame frame;
            RectF srcRect(x * iw, y * ih, width * iw, height * ih);
            RectF destF = Rect(-frameX, -frameY, width, height).cast<RectF>();

            Diffuse df;
            df.base = _texture;
            frame.init(resAnim, df, srcRect, destF, Vector2((float)frameWidth, (float)frameHeight));
            frames.push_back(frame);

            sub = sub.next_sibling();
        }

        if (resAnim)
        {
            resAnim->init(frames, (int)frames.size());
            resAnim->setParent(this);
            context.resources->add(resAnim);
        }
    }
Beispiel #7
0
void ProgXrayImport::run()
{
    // Delete output stack if it exists
    fnOut = fnRoot + ".mrc";
    fnOut.deleteFile();

    /* Turn off error handling */
    H5Eset_auto(H5E_DEFAULT, NULL, NULL);

    if (dSource == MISTRAL)
        H5File.openFile(fnInput, H5F_ACC_RDONLY);


    // Reading bad pixels mask
    if ( !fnBPMask.empty() )
    {
        std::cerr << "Reading bad pixels mask from "+fnBPMask << "." << std::endl;
        bpMask.read(fnBPMask);
        if ( (cropSizeX + cropSizeY ) > 0 )
            bpMask().selfWindow(cropSizeY,cropSizeX,
                                (int)(YSIZE(bpMask())-cropSizeY-1),(int)(XSIZE(bpMask())-cropSizeX-1));
        STARTINGX(bpMask()) = STARTINGY(bpMask()) = 0;
    }


    // Setting the image projections list
    switch (dSource)
    {
    case MISTRAL:
        {
            inMD.read(fnInput);
            H5File.getDataset("NXtomo/data/rotation_angle", anglesArray, false);
            H5File.getDataset("NXtomo/instrument/sample/ExpTimes", expTimeArray, false);
            H5File.getDataset("NXtomo/instrument/sample/current", cBeamArray);

            /* In case there is no angles information we set them to to an increasing sequence
             * just to be able to continue importing data */
            if ( anglesArray.size() != inMD.size() )
            {
                reportWarning("Input file does not contains angle information. Default sequence used.");
                anglesArray.resizeNoCopy(inMD.size());
                anglesArray.enumerate();
            }

            // If expTime is empty or only one single value in nexus file then we fill with 1
            if (expTimeArray.size() < 2)
            {
                reportWarning("Input file does not contains tomogram exposition time information.");
                expTimeArray.initConstant(anglesArray.size(), 1.);
            }
            // If current is empty or only one single value in nexus file then we fill with 1
            if (cBeamArray.size() < 2)
            {
                reportWarning("Input file does not contains tomogram current beam information.");
                cBeamArray.initConstant(anglesArray.size(), 1.);
            }
            // Since Alba does not provide slit width, we set to ones
            slitWidthArray.initConstant(anglesArray.size(), 1.);
        }
        break;
    case BESSY:
        {
            size_t objId;

            for (size_t i = tIni; i <= tEnd; ++i)
            {
                objId = inMD.addObject();
                inMD.setValue(MDL_IMAGE, fnInput + formatString("/img%d.spe", i), objId);
            }
            break;
        }
    case GENERIC:
        {
            // Get Darkfield
            std::cerr << "Getting darkfield from "+fnInput << " ..." << std::endl;
            getDarkfield(fnInput, IavgDark);
            if (XSIZE(IavgDark())!=0)
                IavgDark.write(fnRoot+"_darkfield.xmp");


            std::vector<FileName> listDir;
            fnInput.getFiles(listDir);
            size_t objId;

            for (size_t i = 0; i < listDir.size(); ++i)
            {
                if (!listDir[i].hasImageExtension())
                    continue;
                objId = inMD.addObject();
                inMD.setValue(MDL_IMAGE, fnInput+"/"+listDir[i], objId);
            }
        }
        break;
    }

    inMD.findObjects(objIds);
    size_t nIm = inMD.size();

    // Create empty output stack file

    getImageInfo(inMD, imgInfo);


    /* Get the flatfield:: We get the FF after the image list because we need the image size to adapt the FF
     * in case they were already cropped.
     */
    if (!fnFlat.empty())
    {
        std::cout << "Getting flatfield from "+fnFlat << " ..." << std::endl;
        getFlatfield(fnFlat,IavgFlat);
        if ( XSIZE(IavgFlat()) != 0 )
        {
            FileName ffName = fnRoot+"_flatfield_avg.xmp";
            IavgFlat.write(ffName);
            fMD.setValue(MDL_IMAGE, ffName, fMD.addObject());
        }
    }

    createEmptyFile(fnOut, imgInfo.adim.xdim-cropSizeXi-cropSizeXe, imgInfo.adim.ydim-cropSizeYi-cropSizeYe, 1, nIm);

    // Process images
    td = new ThreadTaskDistributor(nIm, XMIPP_MAX(1, nIm/30));
    tm = new ThreadManager(thrNum, this);
    std::cerr << "Getting data from " << fnInput << " ...\n";
    init_progress_bar(nIm);
    tm->run(runThread);
    progress_bar(nIm);

    // Write Metadata and angles
    MetaData MDSorted;
    MDSorted.sort(outMD,MDL_ANGLE_TILT);
    MDSorted.write("tomo@"+fnRoot + ".xmd");
    if ( fMD.size() > 0 )
        fMD.write("flatfield@"+fnRoot + ".xmd", MD_APPEND);

    // We also reference initial and final images at 0 degrees for Mistral tomograms
    if ( dSource == MISTRAL )
    {
        fMD.clear();
        FileName degree0Fn = "NXtomo/instrument/sample/0_degrees_initial_image";
        if ( H5File.checkDataset(degree0Fn.c_str()))
            fMD.setValue(MDL_IMAGE, degree0Fn + "@" + fnInput, fMD.addObject());
        degree0Fn = "NXtomo/instrument/sample/0_degrees_final_image";
        if ( H5File.checkDataset(degree0Fn.c_str()))
            fMD.setValue(MDL_IMAGE, degree0Fn + "@" + fnInput, fMD.addObject());
        if ( fMD.size() > 0 )
            fMD.write("degree0@"+fnRoot + ".xmd", MD_APPEND);
    }

    // Write tlt file for IMOD
    std::ofstream fhTlt;
    fhTlt.open((fnRoot+".tlt").c_str());
    if (!fhTlt)
        REPORT_ERROR(ERR_IO_NOWRITE,fnRoot+".tlt");
    FOR_ALL_OBJECTS_IN_METADATA(MDSorted)
    {
        double tilt;
        MDSorted.getValue(MDL_ANGLE_TILT,tilt,__iter.objId);
        fhTlt << tilt << std::endl;
    }
    fhTlt.close();
    delete td;
    delete tm;
}
Beispiel #8
0
void ProgXrayImport::getFlatfield(const FileName &fnFFinput,
                                  Image<double> &Iavg)
{

    // Process the flatfield images


    MultidimArray<double> &mdaIavg = Iavg();

    Matrix1D<double> expTimeArray, cBeamArray, slitWidthArray; // Local vectors

    DataSource ldSource = dSource;

    // Checking if fnFFinput is a single file to obtain the flatfield avg from
    if (extFlat && isImage(fnFFinput))
    {
        fMD.read(fnFFinput);
        ldSource = NONE;
    }
    else
    {
        switch (ldSource)
        {
        case MISTRAL:
            if (!H5File.checkDataset(fnFFinput.getBlockName().c_str()))
                break;
            {
                fMD.read(fnFFinput);
                H5File.getDataset("NXtomo/instrument/bright_field/ExpTimes", expTimeArray, false);
                H5File.getDataset("NXtomo/instrument/bright_field/current", cBeamArray, false);

                // If expTime is empty or only one single value in nexus file then we fill with 1
                if (expTimeArray.size() < 2)
                {
                    reportWarning("Input file does not contains flatfields' exposition time information.");
                    expTimeArray.initConstant(fMD.size(), 1.);
                }
                // If current is empty or only one single value in nexus file then we fill with 1
                if (cBeamArray.size() < 2)
                {
                    reportWarning("Input file does not contains flatfields' current beam information.");
                    cBeamArray.initConstant(fMD.size(), 1.);
                }

            }

            // Since Alba does not provide slit width, we set to ones
            slitWidthArray.initConstant(fMD.size(), 1.);

            break;
        case BESSY:
            {
                size_t objId;

                for (size_t i = fIni; i <= fEnd; ++i)
                {
                    objId = fMD.addObject();
                    fMD.setValue(MDL_IMAGE, fnFFinput + formatString("/img%d.spe", i), objId);
                }
                break;
            }
        case GENERIC:
            {
                // Get Darkfield
                std::cout << "Getting darkfield from "+fnFFinput << " ..." << std::endl;
                getDarkfield(fnFFinput, IavgDark);
                if (darkFix)
                    IavgDark.write(fnRoot+"_"+fnFFinput.removeDirectories()+"_darkfield.xmp");

                std::vector<FileName> listDir;
                fnFFinput.getFiles(listDir);
                size_t objId;

                for (size_t i = 0; i < listDir.size(); ++i)
                {
                    if (!listDir[i].hasImageExtension())
                        continue;
                    objId = fMD.addObject();
                    fMD.setValue(MDL_IMAGE, fnFFinput+"/"+listDir[i], objId);
                }
            }
            break;
        }
    }

    if ( fMD.size() == 0 )
    {
        reportWarning("XrayImport::getFlatfield: No images to process");
        return;
    }

    ImageInfo imFFInfo;

    getImageInfo(fMD, imFFInfo);

    if ( (imFFInfo.adim.xdim != imgInfo.adim.xdim) || (imFFInfo.adim.ydim != imgInfo.adim.ydim) )
    {
        reportWarning(formatString("XrayImport:: Flatfield images size %dx%d different from Tomogram images size %dx%d",
                                   imFFInfo.adim.xdim,imFFInfo.adim.ydim,imgInfo.adim.xdim,imgInfo.adim.ydim));
        std::cout << "Setting crop values to fit the smallest dimensions." <<std::endl;

        // This shift in the crop sizes is exclusive of Mistral data
        cropSizeXi = (imgInfo.adim.xdim - std::min(imgInfo.adim.xdim-cropSizeX*2, imFFInfo.adim.xdim))/2 + 1;
        cropSizeYi = (imgInfo.adim.ydim - std::min(imgInfo.adim.ydim-cropSizeY*2, imFFInfo.adim.ydim))/2 + 1;
        cropSizeXe = cropSizeXi - 2;
        cropSizeYe = cropSizeYi - 2;
    }

    int cropX = (imFFInfo.adim.xdim - (imgInfo.adim.xdim-cropSizeXi-cropSizeXe))/2;// - 1;
    int cropY = (imFFInfo.adim.ydim - (imgInfo.adim.ydim-cropSizeYi-cropSizeYe))/2;// - 1;


    int N  = 0;
    Image<double> Iaux;
    FileName fnImg;

    FOR_ALL_OBJECTS_IN_METADATA(fMD)
    {
        fMD.getValue(MDL_IMAGE, fnImg, __iter.objId);

        readAndCrop(fnImg, Iaux, cropX, cropY);


        if ( darkFix )
        {
            Iaux() -= IavgDark();
            forcePositive(Iaux());
        }

        double currentBeam = 1;
        double expTime = 1;
        double slitWidth = 1;

        switch (ldSource)
        {
        case MISTRAL:
            {
                size_t idx = fnImg.getPrefixNumber();
                currentBeam = dMi(cBeamArray, idx-1);
                expTime = dMi(expTimeArray, idx-1);
                slitWidth = dMi(slitWidthArray, idx-1);
            }
            break;
        case BESSY:
        case GENERIC:
            readCorrectionInfo(fnImg, currentBeam, expTime, slitWidth);
            break;
        default:
            break;
        }

        Iaux() *= 1.0/(currentBeam*expTime*slitWidth);

        if ( N == 0 )
            mdaIavg = Iaux();
        else
            mdaIavg += Iaux();
        N++;
    }

    darkFix = false; // We reset just in case there is no dark field for tomo images

    mdaIavg*=1.0/N;

    /* Create a mask with zero valued pixels to apply boundaries median filter
     * to avoid dividing by zero when normalizing */

    MultidimArray<char> &mdaMask = MULTIDIM_ARRAY(bpMask);

    if ( !fnBPMask.empty() && !mdaIavg.sameShape(mdaMask) )
        REPORT_ERROR(ERR_MULTIDIM_SIZE, "XrayImport: Mask size does not match flat fields size.");

    if (BPFactor > 0)
    {
        double  avg, std;
        mdaIavg.computeAvgStdev(avg, std);
        mdaMask.resize(mdaIavg, false);

        double th = avg - std*BPFactor;
        FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(mdaMask)
        dAi(mdaMask, n) = dAi(mdaIavg, n) < th;
    }
    else if (fnBPMask.empty())
        mdaIavg.equal(0,mdaMask);

    MultidimArray<char> mask = mdaMask;
    boundMedianFilter(mdaIavg,mask);
}
Beispiel #9
0
static int internalPut2(WordPutData *put, DFNode *abstract, DFNode *concrete, int isNew,
                        const char *htmlSrc, const char *htmlPath)
{
    int imageChanged = 0;
    int sizeChanged = 0;

    if (!DFFileExists(htmlPath)) {
        WordConverterWarning(put->conv,"HTML image %s does not exist",htmlSrc);
        return 0;
    }

    PixelSize htmlFileSize = PixelSizeZero;
    if (!getImageFile(put->conv,htmlSrc,&htmlFileSize)) {
        WordConverterWarning(put->conv,"Could not get aspect ratio of image: %s",htmlSrc);
        return 0;
    }
    PointsSize htmlSize = pointsSizeFromHTMLImg(put->conv,abstract,htmlFileSize);

    OPCRelationship *rel = NULL;
    const char *drawingId = NULL;

    if (isNew) {
        imageChanged = 1;
        sizeChanged = 1;
    }
    else {
        ImageInfo *wordInfo = getImageInfo(concrete);
        if (wordInfo == NULL)
            return 0;

        rel = OPCRelationshipSetLookupById(put->conv->package->documentPart->relationships,wordInfo->rId);

        if ((wordInfo != NULL) && (wordInfo->widthPts > 0) && (wordInfo->heightPts > 0) && (rel != NULL)) {
            const char *wordSrc = rel->target;
            char *wordPath = DFAppendPathComponent(put->conv->concretePath,wordSrc);

            if (!DFFileExists(wordPath)) {
                WordConverterWarning(put->conv,"Word image %s does not exist",wordSrc);
                free(wordPath);
                ImageInfoFree(wordInfo);
                return 0;
            }

            if (!DFPathContentsEqual(htmlPath,wordPath)) {
                rel->needsRemoveCheck = 1;
                imageChanged = 1;
            }

            if (fabs(wordInfo->widthPts - htmlSize.widthPts) >= 0.1)
                sizeChanged = 1;

            free(wordPath);
        }
        ImageInfoFree(wordInfo);

        if (concrete->tag == WORD_DRAWING)
            drawingId = DrawingInfoDrawingId(concrete);
    }

    if (imageChanged || sizeChanged) {

        if (imageChanged || (rel == NULL)) { // FIXME: is the rel == NULL needed?
            DFError *error = NULL;
            rel = addImageRelationship(put->conv,htmlSrc,&error);
            if (rel == NULL) {
                WordConverterWarning(put->conv,"%s",DFErrorMessage(&error));
                return 0;
            }
        }

        if (drawingId == NULL)
            drawingId = WordObjectsAddDrawing(put->conv->objects)->drawingId;

        populateDrawingElement(put->conv,concrete,htmlSize.widthPts,htmlSize.heightPts,
                               drawingId,rel->rId);
    }

    return 1;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
  image myPic;
  imageInfo picInfo;
  int count;
  char *outputType = NULL;
  int err;
  int aCrop = NO;
  int left = -1, right = -1, top = -1, bottom = -1;
  double xscale = 1, yscale = 1;
  double xs2, ys2;
  int xdim = 0, ydim = 0;
  int ditherMode = ' ';
  int mMono = NO;
  int outType = NO;
  int scaletofit = NO;
  int numBits = 1;
  char *outFile = NULL;
  char *type = NULL, *ext = NULL;
  char *p;
  int nv;
  double darken = 0;
  double contrast = 0;
  double rotate = 0;
  struct stat sbuf;
  int blend = NO;
  static char filename[MAXPATHLEN + 1] = "";
  int negative = NO;
  int enhance = NO;
  formatInfo fInfo;
  

  count = getargs(argc, argv, "nbosabLiRiTiBixdydXiYidcmbpbsbbiDdSbKdfseird",
		   &negative, &outputType, &aCrop, &left, &right, &top,
		   &bottom, &xscale, &yscale, &xdim, &ydim, &ditherMode,
		   &mMono, &outType, &scaletofit, &numBits, &darken,
		   &blend, &contrast, &outFile, &enhance, &rotate
		   );

  if (count < 0 || count == argc) {
    if (count < 0 && -count != '-')
      fprintf(stderr, "Bad flag: %c\n", -count);
    fprintf(stderr, "Usage: %s [-options] filename\n"
	     "  options:\n"
	     "\tn: make negative\n"
	     "\to: string indicating output format\n"
	     "\ta: auto crop non plotting areas\n"
	     "\tL, R, T, B: specify where to crop picture\n"
	     "\tx, y: specify scale factor in that direction\n"
	     "\tX, Y: specify dimension of picture in that direction\n"
	     "\td: select dither method: (D)ither, (T)hreshold, or (H)alftone\n"
	     "\tm: convert image to monochrome\n"
	     "\tp: dither image for output to printer\n"
	     "\ts: scale image to fill up specified screen\n"
	     "\tb: number of bits to dither to\n"
	     "\tD: how much to brighten image\n"
	     "\tK: contrast level\n"
	     "\tS: blend pixels together when scaling\n"
	     "\tf: file name to save to\n"
	     "\te: contrast for enhance image\n"
	     "\tr: number of degrees to rotate\n"
	     , *argv);
    exit(1);
  }

  for (; count < argc; count++) {
    if ((err = load_pic(argv[count], &myPic))) {
      fprintf(stderr, "Cannot load file %s\nError: %s\n", argv[count], picErrorStr(err));
      exit(1);
    }
    
    if (!getImageInfo(argv[count], &picInfo))
      type = picInfo.extension;

    if (!outputType) 
      outputType =  type;

    if (!infoForFormat(outputType, &fInfo)) {
      ext = fInfo.extension;
      if (scaletofit && !xdim && !ydim && fInfo.maxWidth && fInfo.maxHeight) {
	xdim = fInfo.maxWidth;
	ydim = fInfo.maxHeight;
      }
    }
    
    if (mMono)
      makeMono(&myPic);
    
    if (left >= 0 || right >= 0 || top >= 0 || bottom >= 0) {
      if (left < 0)
	left = 0;
      if (right < 0)
	right = myPic.width - 1;
      if (top < 0)
	top = 0;
      if (bottom < 0)
	bottom = myPic.height - 1;
      cropImage(left, top, right, bottom, &myPic);
    }
    
    if (aCrop)
      autoCropImage(&myPic, 40);

    if (rotate)
      rotateImage(&myPic, (rotate * -3.141592) / 180.0);
    
    xs2 = xscale;
    ys2 = yscale;
    if (scaletofit) {
      if (!ydim && xdim) {
	xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale;
	ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale;
      }
      else if (ydim) {
	xs2 = ((double) ydim / ((double) myPic.height * yscale)) * xscale;
	ys2 = (double) ydim / ((double) myPic.height * yscale) * yscale;
	if (xdim && (myPic.width * xs2) > xdim) {
	  xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale;
	  ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale;
	}
      }
    }
    else {
      if (xdim)
	xs2 = (double) xdim / (double) myPic.width;
      if (ydim)
	ys2 = (double) ydim / (double) myPic.height;
    }
    xscale = xs2;
    yscale = ys2;

    scaleImage(xscale, yscale, blend, &myPic);

    if (darken || contrast)
      adjustImage(&myPic, contrast, darken);
    if (enhance) {
      makeMono(&myPic);
      enhanceImage(&myPic, enhance);
    }
    
    handle_dithering(ditherMode, &myPic, outType, numBits);
    if (negative)
      negateImage(&myPic);

    if (outFile) {
      strcpy(filename, outFile);
      if (!stat(filename, &sbuf) && (sbuf.st_mode & S_IFDIR)) {
	if (filename[strlen(filename) - 1] != '/')
	  strcat(filename, "/");
	if ((p = strrchr(argv[count], '/')))
	  strcat(filename, p + 1);
	else
	  strcat(filename, argv[count]);
      }
    }
    else
      strcpy(filename, argv[count]);
    
    p = change_extension(filename, type, ext, 0);
    nv = 2;
    while (!stat(p, &sbuf)) {
      p = change_extension(filename, type, ext, nv);
      nv++;
    }

    if ((err = save_pic(p, outputType, &myPic))) {
      fprintf(stderr, "Cannot save file %s\nError: %s\n", p, picErrorStr(err));
      exit(1);
    }

    fprintf(stderr, "Saved %s as %s\n", argv[count], p);

    freeImage(&myPic);
  }

  exit(0);
  return 0;
}
void Images::thumbStart_r ( bool amThread ) {

	int64_t start = gettimeofdayInMilliseconds();

	//static char  scmd[200] = "%stopnm %s | "
	//                         "pnmscale -xysize 100 100 - | "
	//                         "ppmtojpeg - > %s";

	
	log( LOG_DEBUG, "image: thumbStart_r entered." );

	//DIR  *d;
	//char  cmd[2500];
	//sprintf( cmd, "%strash", g_hostdb.m_dir );

	makeTrashDir();

	// get thread id. pthread_t is 64 bit and pid_t is 32 bit on
	// 64 bit oses
	pthread_t id = pthread_self();

	// pass the input to the program through this file
	// rather than a pipe, since popen() seems broken.
	// m_dir ends in / so this should work.
	char in[364];
	snprintf ( in , 363,"%strash/in.%" PRId64
		   , g_hostdb.m_dir, (int64_t)id );
	unlink ( in );

	log( LOG_DEBUG, "image: thumbStart_r create in file." );

	// collect the output from the filter from this file
	// m_dir ends in / so this should work.
	char out[364];
	snprintf ( out , 363,"%strash/out.%" PRId64
		   , g_hostdb.m_dir, (int64_t)id );
        unlink ( out );

	log( LOG_DEBUG, "image: thumbStart_r create out file." );

        // ignore errno from those unlinks        
        errno = 0;

        // Open/Create temporary file to store image to
        int   fhndl;
        if( (fhndl = open( in, O_RDWR+O_CREAT ,
			   getFileCreationFlags()
			   // //			   S_IWUSR+S_IRUSR 
			   )) < 0 ) {
               log( "image: Could not open file, %s, for writing: %s - %d.",
       		    in, mstrerror( m_errno ), fhndl );
	       m_imgDataSize = 0;
       	       return;
        }

        // Write image data into temporary file
        if( write( fhndl, m_imgData, m_imgDataSize ) < 0 ) {
               log( "image: Could not write to file, %s: %s.",
       		    in, mstrerror( m_errno ) );
       	       close( fhndl );
	       unlink( in );
	       m_imgDataSize = 0;
       	       return;
        }

        // Close temporary image file now that we have finished writing
        if( close( fhndl ) < 0 ) {
               log( "image: Could not close file, %s, for writing: %s.",
       	            in, mstrerror( m_errno ) );
	       unlink( in );
	       m_imgDataSize = 0;
      	       return;
        }
	fhndl = 0;

        // Grab content type from mime
	//int32_t imgType = mime.getContentType();
        char  ext[5];
        switch( m_imgType ) {
               case CT_GIF:
		       strcpy( ext, "gif" );
	               break;
               case CT_JPG:
		       strcpy( ext, "jpeg" );
		       break;
               case CT_PNG:
		       strcpy( ext, "png" );
		       break;
               case CT_TIFF:
		       strcpy( ext, "tiff" );
		       break;
	       case CT_BMP:
		       strcpy( ext, "bmp" );
		       break;
        } 

	// i hope 2500 is big enough!
	char  cmd[2501];

	//sprintf( cmd, scmd, ext, in, out);
	char *wdir = g_hostdb.m_dir;
	// can be /dev/stderr or like /var/gigablast/data/log000 etc.
	const char *logFile = g_log.getFilename();
	// wdir ends in / so this should work.
	snprintf( cmd, 2500 ,
		 "LD_LIBRARY_PATH=%s %s%stopnm %s 2>> %s | "
		 "LD_LIBRARY_PATH=%s %spnmscale -xysize %" PRId32" %" PRId32" - 2>> %s | "
		  // put all its stderr msgs into /dev/null
		  // so "jpegtopnm: WRITING PPM FILE" doesn't clog console
		 "LD_LIBRARY_PATH=%s %sppmtojpeg - > %s 2>> %s"
		  , wdir , wdir , ext , in , logFile
		  , wdir , wdir , m_xysize , m_xysize , logFile
		  , wdir , wdir , out , logFile
		 );

	// if they already have netpbm package installed use that then
	static bool s_checked = false;
	static bool s_hasNetpbm = false;
	if ( ! s_checked ) {
		s_checked = true;
		File f;
		f.set("/usr/bin/pnmscale");
		s_hasNetpbm = f.doesExist() ;
	}
	if ( s_hasNetpbm )
		snprintf( cmd, 2500 ,
			  "%stopnm %s 2>> %s | "
			  "pnmscale -xysize %" PRId32" %" PRId32" - 2>> %s | "
			  "ppmtojpeg - > %s 2>> %s"
			  , ext , in , logFile
			  , m_xysize , m_xysize , logFile
			  , out , logFile
			  );
		
        
        // Call clone function for the shell to execute command
	int err = system( cmd ); // m_thmbconvTimeout );

	//if( (m_dx != 0) && (m_dy != 0) )
	//	unlink( in );
	unlink ( in );

	if ( err == 127 ) {
		m_errno = EBADENGINEER;
		log("image: /bin/sh does not exist.");
		unlink ( out );
		m_stopDownloading = true;
		return;
	}
	// this will happen if you don't upgrade glibc to 2.2.4-32 or above
	if ( err != 0 ) {
		m_errno = EBADENGINEER;
		log("image: Call to system(\"%s\") had error.",cmd);
		unlink ( out );
		m_stopDownloading = true;
		return;
	}

        // Open new file with thumbnail image
        if( (fhndl = open( out, O_RDONLY )) < 0 ) {
               log( "image: Could not open file, %s, for reading: %s.",
		    out, mstrerror( m_errno ) );
		unlink ( out );
		m_stopDownloading = true;
	       return;
        }

	if( (m_thumbnailSize = lseek( fhndl, 0, SEEK_END )) < 0 ) {
		log( "image: Seek of file, %s, returned invalid size: %" PRId32,
		     out, m_thumbnailSize );
		m_stopDownloading = true;
		close(fhndl);
		unlink ( out );
		return;
	}

	if( m_thumbnailSize > m_imgReplyMaxLen ) {
		log(LOG_DEBUG,"image: Image thumbnail larger than buffer!" );
		log(LOG_DEBUG,"image: File Read Bytes: %" PRId32, m_thumbnailSize);
		log(LOG_DEBUG,"image: Buf Max Bytes  : %" PRId32,m_imgReplyMaxLen );
		log(LOG_DEBUG,"image: -----------------------" );
		log(LOG_DEBUG,"image: Diff           : %" PRId32,
		     m_imgReplyMaxLen-m_thumbnailSize );
		close(fhndl);
		unlink ( out );
		return;

	}

	if( lseek( fhndl, 0, SEEK_SET ) < 0 ) {
		log( "image: Seek couldn't rewind file, %s.", out );
		m_stopDownloading = true;
		close(fhndl);
		unlink ( out );
		return;
	}

        // . Read contents back into image ptr
	// . this is somewhat of a hack since it overwrites the original img
        if( (m_thumbnailSize = read( fhndl, m_imgData, m_imgDataSize )) < 0 ) {
                log( "image: Could not read from file, %s: %s.",
 		     out, mstrerror( m_errno ) );
	        close( fhndl );
		m_stopDownloading = true;
		unlink( out );
	        return;
        }

        if( close( fhndl ) < 0 ) {
                log( "image: Could not close file, %s, for reading: %s.",
 		     out, mstrerror( m_errno ) );
		unlink( out );
		m_stopDownloading = true;
		unlink ( out );
 	        return;
        }
	fhndl = 0;
       	unlink( out );
	int64_t stop = gettimeofdayInMilliseconds();
	// tell the loop above not to download anymore, we got one
	m_thumbnailValid = true;

	// MDW: this was m_imgReply
	getImageInfo ( m_imgData , m_thumbnailSize , &m_tdx , &m_tdy , NULL );

	// now make the meta data struct
	// <imageUrl>\0<width><height><thumbnailData>
	


	log( LOG_DEBUG, "image: Thumbnail size: %" PRId32" bytes.", m_imgDataSize );
	log( LOG_DEBUG, "image: Thumbnail dx=%" PRId32" dy=%" PRId32".", m_tdx,m_tdy );
	log( LOG_DEBUG, "image: Thumbnail generated in %" PRId64"ms.", stop-start );
}
bool Images::makeThumb ( ) {
	// did it have an error?
	if ( g_errno ) {
		// just give up on all of them if one has an error
		log ( "image: had error downloading image on page %s: %s. "
		      "Not downloading any more.",
		      m_pageUrl->getUrl(),mstrerror(g_errno));
		// stop it
		m_stopDownloading = true;
		return true;
	}
	char *buf;
	int32_t  bufLen, bufMaxLen;
	HttpMime mime;
	m_imgData     = NULL;
	m_imgDataSize = 0;

	log( LOG_DEBUG, "image: gotImage() entered." );
	// . if there was a problem, just ignore, don't let it stop getting
	//   the real page.
	if ( g_errno ) {
		log( "ERROR? g_errno puked: %s", mstrerror(g_errno) );
		//g_errno = 0;
		return true;
	}
	//if ( ! slot ) return true;
	// extract image data from the socket
	buf       = m_msg13.m_replyBuf;
	bufLen    = m_msg13.m_replyBufSize;
	bufMaxLen = m_msg13.m_replyBufAllocSize;
	// no image?
	if ( ! buf || bufLen <= 0 ) {
		g_errno = EBADIMG;
		return true;
	}
	// we are image candidate #i
	//int32_t i = m_j - 1;
	// get img tag node
	// get the url of the image
	int32_t  srcLen;
	char *src = getImageUrl ( m_j , &srcLen );
	// set it to the full url
	Url iu;
	// use "pageUrl" as the baseUrl
	iu.set( m_pageUrl, src, srcLen );
	// get the mime
	if ( ! mime.set ( buf, bufLen, &iu ) ) {		
		log ( "image: MIME.set() failed in gotImage()" );
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// set the status so caller can see
	int32_t httpStatus = mime.getHttpStatus();
	// check the status
	if ( httpStatus != 200 ) {
		log( LOG_DEBUG, "image: http status of img download is %" PRId32".",
		     m_httpStatus);
		// give up on the remaining images then
		m_stopDownloading = true;
		g_errno = EBADIMG;
		return true;
	}
	// make sure this is an image
	m_imgType = mime.getContentType();
	if ( m_imgType < CT_GIF || m_imgType > CT_TIFF ) {
		log( LOG_DEBUG, "image: gotImage() states that this image is "
		     "not in a format we currently handle." );
		// try the next image if any
		g_errno = EBADIMG;
		return true;
	}
	// get the content
	m_imgData     = buf + mime.getMimeLen();
	m_imgDataSize = bufLen - mime.getMimeLen();
	// Reset socket, so socket doesn't free the data, now we own
	// We must free the buf after thumbnail is inserted in TitleRec
	m_imgReply       = buf;//slot->m_readBuf;
	m_imgReplyLen    = bufLen;//slot->m_readBufSize;
	m_imgReplyMaxLen = bufMaxLen;//slot->m_readBufMaxSize;
	// do not let UdpServer free the reply, we own it now
	//slot->m_readBuf = NULL;

	if ( ! m_imgReply || m_imgReplyLen == 0 ) {
		log( LOG_DEBUG, "image: Returned empty image reply!" );
		g_errno = EBADIMG;
		return true;
	}

	// get next if too small
	if ( m_imgDataSize < 20 ) { g_errno = EBADIMG; return true; }

	int32_t imageType;
	getImageInfo ( m_imgData, m_imgDataSize, &m_dx, &m_dy, &imageType );

	// log the image dimensions
	log( LOG_DEBUG,"image: Image Link: %s", iu.getUrl() );
	log( LOG_DEBUG,"image: Max Buffer Size: %" PRIu32" bytes.",m_imgReplyMaxLen);
	log( LOG_DEBUG,"image: Image Original Size: %" PRIu32" bytes.",m_imgReplyLen);
	log( LOG_DEBUG,"image: Image Buffer @ 0x%" PTRFMT" - 0x%" PTRFMT"",(PTRTYPE)m_imgReply,
	     (PTRTYPE)(m_imgReply+m_imgReplyMaxLen) );
	log( LOG_DEBUG, "image: Size: %" PRIu32"px x %" PRIu32"px", m_dx, m_dy );

	// what is this?
	if ( m_dx <= 0 || m_dy <= 0 ) {
		log(LOG_DEBUG, "image: Image has bad dimensions.");
		g_errno = EBADIMG;
		return true;
	}


	// skip if bad dimensions
	if( ((m_dx < 50) || (m_dy < 50)) && ((m_dx > 0) && (m_dy > 0)) ) {
		log(LOG_DEBUG,
		    "image: Image is too small to represent a news article." );
		g_errno = EBADIMG;
		return true;
	}

	// skip if bad aspect ratio. 5x1 or 1x5 is bad i guess
	if ( m_dx > 0 && m_dy > 0 ) {
		float aspect = (float)m_dx / (float)m_dy;
		if ( aspect < .2 || aspect > 5.0 ) {
			log(LOG_DEBUG,
			    "image: Image aspect ratio is worse that 5 to 1");
			g_errno = EBADIMG;
			return true;
		}
	}

	CollectionRec *cr = g_collectiondb.getRec(m_collnum);
	if ( ! cr ) { g_errno = ENOCOLLREC; return true; }

	// save how big of thumbnails we should make. user can change
	// this in the 'spider controls'
	m_xysize = cr->m_thumbnailMaxWidthHeight ;
	// make it 250 pixels if no decent value provided
	if ( m_xysize <= 0 ) m_xysize = 250;
	// and keep it sane
	if ( m_xysize > 2048 ) m_xysize = 2048;

	// update status
	if ( m_xd ) m_xd->setStatus ( "making thumbnail" );
	// log it
	log ( LOG_DEBUG, "image: gotImage() thumbnailing image." );
	// create the thumbnail...
	// reset this... why?
	g_errno = 0;
	// reset this since filterStart_r() will set it on error
	m_errno = 0;
	// callThread returns true on success, in which case we block
	if ( g_jobScheduler.submit(thumbStartWrapper_r,
	                           makeThumbWrapper,
				   this,
				   thread_type_generate_thumbnail,
				   MAX_NICENESS) )
		return false;
	// threads might be off
	logf ( LOG_DEBUG, "image: Calling thumbnail gen without thread.");
	thumbStartWrapper_r ( this );
	return true;
}
Beispiel #13
0
  std::error_code perform(SimpleFile &mergedFile) override {
    // Add the image info.
    mergedFile.addAtom(*getImageInfo());

    return std::error_code();
  }
int main(int argc, char* argv[]) {
	/** Start profiling cycle & energy using VarEMU **/
	vemu_read(READ_PROC, &start);
	/*****************************************/

	FILE	*bmpInput, *bmpOutput;
	sImage originalImage;
	sImage edgeImage;
	int nColors, SUM;
	unsigned long vectorSize;
	unsigned long fileSize, fileSize2;
	unsigned char *pChar, someChar;
	unsigned int row, col;

	someChar = '0'; pChar = &someChar;

	if(argc < 2) {
		printf("Usage: %s bmpInput.bmp\n", argv[0]);
		exit(0);
	};
	printf("Reading filename %s\n", argv[1]);

	/*-------DECLARE INPUT & OUTPUT FILES-------*/
	bmpInput = fopen(argv[1], "rb");
	bmpOutput = fopen("output.bmp", "wb");
	if(bmpOutput == NULL) {
	   printf("opening file failed \n");
	   return;
	}
	/*---SET POINTER TO BEGINNING OF FILE----*/
	fseek(bmpInput, 0L, SEEK_END);

	/*-------GET INPUT BMP DATA--------*/
	fileSize = getImageInfo(bmpInput, 2, 4);
	originalImage.cols = (int)getImageInfo(bmpInput, 18, 4);
	originalImage.rows = (int)getImageInfo(bmpInput, 22, 4);
	edgeImage.rows = originalImage.rows;
	edgeImage.cols = originalImage.cols;

	/*--------PRINT DATA TO SCREEN----------*/
	printf("Width: %d\n", originalImage.cols);
	printf("Height: %d\n", originalImage.rows);
	printf("File size: %lu\n", fileSize);

	nColors = (int)getImageInfo(bmpInput, 46, 4);
	printf("nColors: %d\n", nColors);

	/*------ALLOCATE MEMORY FOR FILES--------*/
	vectorSize = fileSize - (14+40+4*nColors);
	printf("vectorSize: %lu\n", vectorSize);
	// edgeImage.data = farmalloc(vectorSize*sizeof(unsigned char));
	edgeImage.data = (unsigned char*) malloc(vectorSize*sizeof(unsigned char));
	if(edgeImage.data == NULL) {
		printf("Failed to malloc edgeImage.data\n");
		exit(0);
	}
	printf("%lu bytes malloc'ed for edgeImage.data\n", vectorSize);

	// originalImage.data = farmalloc(vectorSize*sizeof(unsigned char));
	originalImage.data = (unsigned char*) malloc(vectorSize*sizeof(unsigned char));
	if(originalImage.data == NULL) {
		printf("Failed to malloc originalImage.data\n");
		exit(0);
	}
	printf("%lu bytes malloc'ed for originalImage.data\n", vectorSize);

	/*------COPY HEADER AND COLOR TABLE---------*/
	copyImageInfo(bmpInput, bmpOutput);

	copyColorTable(bmpInput, bmpOutput, nColors);

	fseek(bmpInput, (14+40+4*nColors), SEEK_SET);

	fseek(bmpOutput, (14+40+4*nColors), SEEK_SET);

	/* Read input.bmp and store it's raster data into originalImage.data */
	for(row=0; row<=originalImage.rows-1; row++) {
		for(col=0; col<=originalImage.cols-1; col++) {
			fread(pChar, sizeof(char), 1, bmpInput);
			*(originalImage.data + row*originalImage.cols + col) = *pChar;
		}
	}

	/*---------------------------------------------------
	  YOUR EDGE DETECTION ALGORITHM STARTS HERE
	---------------------------------------------------*/
	  
	
	/*---------------------------------------------------
	  YOUR EDGE DETECTION ALGORITHM ENDS HERE
	---------------------------------------------------*/

	/** Stop profiling cycle & energy using VarEMU,
		and print out the results. **/
    vemu_read(READ_PROC, &end);
    printf("\nvaremu cycles: %llu\tenergy: %llu nJ\n", end.total_cycles - start.total_cycles, end.total_act_energy - start.total_act_energy);

    /*****************************************/

	printf("See output.bmp for results\n");
	fclose(bmpInput);
	fclose(bmpOutput);
	// farfree(edgeImage.data);			/* Finished with edgeImage.data */
	// farfree(originalImage.data);	/* Finished with originalImage.data */
	free(edgeImage.data);			/* Finished with edgeImage.data */
	free(originalImage.data);	/* Finished with originalImage.data */
	return 0;
}
ExifStatus ExifImageFile::initAfterOpen( const char* cmode )
{
    /*
     * Default is to return data MSB2LSB
     */
    mExifio->flags() |= FILLORDER_MSB2LSB ;

  /*
   * Process library-specific flags in the open mode std::string.
   * The following flags may be used to control intrinsic library
   * behaviour that may or may not be desirable (usually for
   * compatibility with some application that claims to support
   * EXIF but only supports some braindead idea of what the
   * vendor thinks EXIF is):
   *
   * 'L'        read/write information using LSB2MSB bit order
   * 'B'        read/write information using MSB2LSB bit order
   * 'H'        read/write information using host bit order
   *
   * The 'L', 'B', and 'H' flags are intended for applications
   * that can optimize operations on data by using a particular
   * bit order.  By default the library returns data in MSB2LSB
   * bit order for compatibiltiy with older versions of this
   * library.  Returning data in the bit order of the native cpu
   * makes the most sense but also requires applications to check
   * the value of the FillOrder tag; something they probably do
   * not do right now.
   *
   */
    const char* cp ;
    for(cp = cmode; *cp; cp++)
    {
        switch (*cp) 
        {
            case 'B':
                mExifio->flags() = (mExifio->flags() &~ EXIF_FILLORDER) |
                    FILLORDER_MSB2LSB;
                break;
            case 'L':
                mExifio->flags() = (mExifio->flags() &~ EXIF_FILLORDER) |
                    FILLORDER_LSB2MSB;
                break;
            case 'H':
                mExifio->flags() = (mExifio->flags() &~ EXIF_FILLORDER) |
                    HOST_FILLORDER;
                break;
        }
    }

    mAppSegManager->clear() ;

    // Check the endianness of the current architechture
    // HOST_BIGENDIAN is a configuration setting, true
    // if native cpu byte order is big endian, false if little
    bool bigendian = HOST_BIGENDIAN ;
    initEndian( bigendian );
    ExifStatus status ;
    
    // Setup for writing new 
    if( mExifio->mode() & O_CREAT )
    {
        status = initAppSegs( mExifio ) ;
        /* END OF Setting up a new file for writing */
    }
    else if( (mExifio->mode() & O_RDWR) && (ExifImageFile::isExifFile(mExifio)
        != EXIF_OK) && (ExifJpegImage::isJpegFile( mExifio ) == EXIF_OK) )
    {
        // If we have a plain Jpeg non Exif file (JFIF) opened in ReadWrite
        // mode, then we need to initialize the app segments for it as if we
        // were creating a new file. To do this we create a temp ExifIO* in
        // "w" mode and pass it to initAppSegs so that it behaves as if we
        // were creating a new exif file. Nothing is written to this temp
        // ExifIO.
        char buf[20];
        ExifIO * tmpExifIO = new ExifIO(status,buf,20, "w");
        if( status == EXIF_OK )
        {
            tmpExifIO->flags() = mExifio->flags();
            status = initAppSegs( tmpExifIO );
            tmpExifIO->close();
            delete tmpExifIO;
            if( status == EXIF_OK )
            {        
                status = ExifJpegImage::initAfterOpen( cmode ) ;
     
                /* The following code checks the real height and width and 
                   inserts it into the appropriate tags (in case they are 
                   incorrect). This forces a conversion of the Tiff App Seg 
                   from Raw form... Do we want to do this??? rlr */
                if ( status == EXIF_OK )
                {
                    // Set the value of EXIFTAG_PIXELXDIMENSION and 
                    // EXIFTAG_PIXELYDIMENSION to match the value in 
                    // the Jpeg Marker.
                    ExifImageInfo imgInfo ;
                    if ( getImageInfo( imgInfo ) == EXIF_OK )
                    {
                        ExifTagEntry * tagEntry = new ExifTagEntryT<exif_uint32>
                            ( EXIFTAG_PIXELXDIMENSION, EXIF_LONG, 1, 
                              imgInfo.width );
                        setGenericTag(*tagEntry,EXIF_APP1_EXIFIFD);
                        delete tagEntry ;
                        tagEntry = new ExifTagEntryT<exif_uint32>
                            ( EXIFTAG_PIXELYDIMENSION, EXIF_LONG, 1, 
                              imgInfo.height );
                        setGenericTag(*tagEntry,EXIF_APP1_EXIFIFD);
                        delete tagEntry ;
                    }
                }  
            }
        }          

    }
    else
    {
//         readSOI(mExifio) ;
// 
//         if( (status = readAppSegs(mExifio)) == EXIF_OK )
//             status = ExifJpegImage::initAfterOpen( cmode ) ;
        status = readImage();
    }

    return status;
}
void Images::thumbStart_r ( bool amThread ) {

	long long start = gettimeofdayInMilliseconds();

	//static char  scmd[200] = "%stopnm %s | "
	//                         "pnmscale -xysize 100 100 - | "
	//                         "ppmtojpeg - > %s";

	
	log( LOG_DEBUG, "image: thumbStart_r entered." );

	//DIR  *d;
	//char  cmd[2500];
	//sprintf( cmd, "%strash", g_hostdb.m_dir );

	makeTrashDir();

	// get thread id
	long id = getpidtid();

	// pass the input to the program through this file
	// rather than a pipe, since popen() seems broken
	char in[364];
	snprintf ( in , 363,"%strash/in.%li", g_hostdb.m_dir, id );
	unlink ( in );

	log( LOG_DEBUG, "image: thumbStart_r create in file." );

	// collect the output from the filter from this file
	char out[364];
	snprintf ( out , 363,"%strash/out.%li", g_hostdb.m_dir, id );
        unlink ( out );

	log( LOG_DEBUG, "image: thumbStart_r create out file." );

        // ignore errno from those unlinks        
        errno = 0;

        // Open/Create temporary file to store image to
        int   fhndl;
        if( (fhndl = open( in, O_RDWR+O_CREAT, S_IWUSR+S_IRUSR )) < 0 ) {
               log( "image: Could not open file, %s, for writing: %s - %d.",
       		    in, mstrerror( m_errno ), fhndl );
	       m_imgDataSize = 0;
       	       return;
        }

        // Write image data into temporary file
        if( write( fhndl, m_imgData, m_imgDataSize ) < 0 ) {
               log( "image: Could not write to file, %s: %s.",
       		    in, mstrerror( m_errno ) );
       	       close( fhndl );
	       unlink( in );
	       m_imgDataSize = 0;
       	       return;
        }

        // Close temporary image file now that we have finished writing
        if( close( fhndl ) < 0 ) {
               log( "image: Could not close file, %s, for writing: %s.",
       	            in, mstrerror( m_errno ) );
	       unlink( in );
	       m_imgDataSize = 0;
      	       return;
        }
	fhndl = 0;

        // Grab content type from mime
	//long imgType = mime.getContentType();
        char  ext[5];
        switch( m_imgType ) {
               case CT_GIF:
		       strcpy( ext, "gif" );
	               break;
               case CT_JPG:
		       strcpy( ext, "jpeg" );
		       break;
               case CT_PNG:
		       strcpy( ext, "png" );
		       break;
               case CT_TIFF:
		       strcpy( ext, "tiff" );
		       break;
	       case CT_BMP:
		       strcpy( ext, "bmp" );
		       break;
        } 

	long xysize = 250;//100;
	// make thumbnail a little bigger for diffbot for widget
	if ( m_xd->m_isDiffbotJSONObject ) xysize = 250;

	// i hope 2500 is big enough!
	char  cmd[2501];

	//sprintf( cmd, scmd, ext, in, out);
	char *wdir = g_hostdb.m_dir;
	snprintf( cmd, 2500 ,
		 "LD_LIBRARY_PATH=%s %s/%stopnm %s | "
		 "LD_LIBRARY_PATH=%s %s/pnmscale -xysize %li %li - | "
		 "LD_LIBRARY_PATH=%s %s/ppmtojpeg - > %s"
		 , wdir , wdir , ext , in
		 , wdir , wdir , xysize , xysize
		 , wdir , wdir , out
		 );
        
        // Call clone function for the shell to execute command
        // This call WILL BLOCK	. timeout is 30 seconds.
	//int err = my_system_r( cmd, 30 ); // m_thmbconvTimeout );
	int err = system( cmd ); // m_thmbconvTimeout );

	//if( (m_dx != 0) && (m_dy != 0) )
	//	unlink( in );
	unlink ( in );

	if ( err == 127 ) {
		m_errno = EBADENGINEER;
		log("image: /bin/sh does not exist.");
		unlink ( out );
		m_stopDownloading = true;
		return;
	}
	// this will happen if you don't upgrade glibc to 2.2.4-32 or above
	if ( err != 0 ) {
		m_errno = EBADENGINEER;
		log("image: Call to system(\"%s\") had error.",cmd);
		unlink ( out );
		m_stopDownloading = true;
		return;
	}

        // Open new file with thumbnail image
        if( (fhndl = open( out, O_RDONLY )) < 0 ) {
               log( "image: Could not open file, %s, for reading: %s.",
		    out, mstrerror( m_errno ) );
	       m_stopDownloading = true;
	       return;
        }

	if( (m_thumbnailSize = lseek( fhndl, 0, SEEK_END )) < 0 ) {
		log( "image: Seek of file, %s, returned invalid size: %ld",
		     out, m_thumbnailSize );
		m_stopDownloading = true;
		close(fhndl);
		return;
	}

	if( m_thumbnailSize > m_imgReplyMaxLen ) {
		log(LOG_DEBUG,"image: Image thumbnail larger than buffer!" );
		log(LOG_DEBUG,"image: File Read Bytes: %ld", m_thumbnailSize);
		log(LOG_DEBUG,"image: Buf Max Bytes  : %ld",m_imgReplyMaxLen );
		log(LOG_DEBUG,"image: -----------------------" );
		log(LOG_DEBUG,"image: Diff           : %ld", 
		     m_imgReplyMaxLen-m_thumbnailSize );
		close(fhndl);
		return;

	}

	if( lseek( fhndl, 0, SEEK_SET ) < 0 ) {
		log( "image: Seek couldn't rewind file, %s.", out );
		m_stopDownloading = true;
		close(fhndl);
		return;
	}

        // . Read contents back into image ptr
	// . this is somewhat of a hack since it overwrites the original img
        if( (m_thumbnailSize = read( fhndl, m_imgData, m_imgDataSize )) < 0 ) {
                log( "image: Could not read from file, %s: %s.",
 		     out, mstrerror( m_errno ) );
	        close( fhndl );
		m_stopDownloading = true;
		unlink( out );
	        return;
        }

        if( close( fhndl ) < 0 ) {
                log( "image: Could not close file, %s, for reading: %s.",
 		     out, mstrerror( m_errno ) );
		unlink( out );
		m_stopDownloading = true;
 	        return;
        }
	fhndl = 0;
       	unlink( out );
	long long stop = gettimeofdayInMilliseconds();
	// tell the loop above not to download anymore, we got one
	m_thumbnailValid = true;

	// MDW: this was m_imgReply
	getImageInfo ( m_imgData , m_thumbnailSize , &m_tdx , &m_tdy , NULL );

	// now make the meta data struct
	// <imageUrl>\0<width><height><thumbnailData>
	


	log( LOG_DEBUG, "image: Thumbnail size: %li bytes.", m_imgDataSize );
	log( LOG_DEBUG, "image: Thumbnail dx=%li dy=%li.", m_tdx,m_tdy );
	log( LOG_DEBUG, "image: Thumbnail generated in %lldms.", stop-start );
}
Beispiel #17
0
void nibbParseImageDir(char *sourceDir, char *goodTab, char *badTab)
/* nibbParseImageDir - Look through nibb image directory and allowing for 
 * typos and the like create a table that maps a file name to clone name, 
 * developmental stage, and view of body part. */
{
struct fileInfo *l1List, *l1, *l2List, *l2, *l3List, *l3;
struct hash *stageHash = hashNew(0);
struct hash *viewHash = hashNew(0);
struct hash *otherHash = hashNew(0);
struct hash *probeHash = hashNew(0);
struct hash *fixHash = hashFixers();
struct imageInfo *imageList = NULL, *image;
FILE *good = mustOpen(goodTab, "w");
FILE *bad = mustOpen(badTab, "w");
int goodCount = 0, badCount = 0;
int jpgCount = 0, jpgDir = 0;


l1List = listDirX(sourceDir, "XL*", FALSE);
for (l1 = l1List; l1 != NULL; l1 = l1->next)
    {
    char l1Path[PATH_LEN];
    safef(l1Path, sizeof(l1Path), "%s/%s", sourceDir, l1->name);
    l2List = listDirX(l1Path, "XL*", FALSE);
    for (l2 = l2List; l2 != NULL; l2 = l2->next)
        {
	char l2Path[PATH_LEN];
	char cloneName[64], *permanentCloneName;
	char *cloneDir = l2->name;
	char *cloneEnd;
	int cloneNameSize = 0;

	if (stringIx(cloneDir, skipDir) >= 0)
	    continue;

	/* Figure out clone name, whish is directory component up to
	 * first underbar. */
	cloneEnd = strchr(cloneDir, '_');
	if (cloneEnd != NULL)
	    cloneNameSize = cloneEnd - cloneDir;
	else
	    errAbort("Strangely formatted image dir %s, no underbar", cloneDir);
	if (cloneNameSize >= sizeof(cloneName))
	    errAbort("Clone name too long in dir %s", cloneDir);
	if (cloneNameSize < 8 || cloneNameSize > 12)
	    errAbort("Clone name wrong size %s", cloneDir);
	memcpy(cloneName, cloneDir, cloneNameSize);
	cloneName[cloneNameSize] = 0;
	/* Check format is XL###L##.  We already checked the XL. */
	if (!isdigit(cloneName[2]) || !isdigit(cloneName[3]) 
		 || !isdigit(cloneName[4]) || isdigit(cloneName[5]) 
		 || !isdigit(cloneName[6]) || !isdigit(cloneName[7]))
	    errAbort("Strangely formatted clone name %s", cloneDir);

	permanentCloneName = hashStoreName(probeHash, cloneName);


	/* Get all files in dir. */
	safef(l2Path, sizeof(l2Path), 
		"%s/%s/%s", sourceDir, l1->name, l2->name);
	l3List = listDirX(l2Path, "*.jpg", FALSE);
	for (l3 = l3List; l3 != NULL; l3 = l3->next)
	    {
	    char *fileName = l3->name;

	    if (stringIx(l3->name, skipFile) >= 0)
		continue;
	    image = getImageInfo(fixHash, permanentCloneName, 
	    	l1->name, cloneDir, fileName,
	    	stageHash, viewHash, otherHash, probeHash);
	    slAddHead(&imageList, image);
	    ++jpgCount;
	    }
	++jpgDir;
	}
    }
slReverse(&imageList);

verbose(1, "%d jpg images in %d directories\n", jpgCount, jpgDir);

#ifdef OLD
verbose(1, "%d probes, %d stages, %d views, %d other\n", 
	probeHash->elCount, stageHash->elCount, 
	viewHash->elCount, otherHash->elCount);
printHash("stages", stageHash);
printHash("views", viewHash);
printHash("other", otherHash);
#endif /* OLD */

for (image = imageList; image != NULL; image = image->next)
    {
    if (image->clone != NULL && image->stage != NULL && image->view != NULL)
        {
	imageInfoOut(image, good);
	++goodCount;
	}
    else
	{
	imageInfoOut(image, bad);
	++badCount;
	}
    }
verbose(1, "%d (%4.1f%%) parsed ok, %d (%4.2f%%) didn't\n", 
	goodCount, 100.0 * goodCount/(goodCount + badCount), 
	badCount, 100.0 * badCount/(goodCount + badCount));
carefulClose(&good);
carefulClose(&bad);
}
Beispiel #18
0
static JSBool
jsImageToPS( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval )
{
    static char const usage[] = {
        "Usage: imageToPS( { image: data, x:0, y:0, w:10, h:10 } ) );\n"
    };

    *rval = JSVAL_FALSE ;
    jsUsblpPoll_t *dev = (jsUsblpPoll_t *)JS_GetInstancePrivate( cx, obj, &jsUsblpClass_, NULL );
    if( dev )
    {
        JSObject *paramObj ;
        if( ( 1 == argc )
                &&
                JSVAL_IS_OBJECT(argv[0])
                &&
                ( 0 != ( paramObj = JSVAL_TO_OBJECT(argv[0]) ) ) )
        {
            JSString *sImageData ;
            unsigned x, y ;
            jsval val ;
            if( JS_GetProperty( cx, paramObj, "x", &val )
                    &&
                    ( x = JSVAL_TO_INT(val), JSVAL_IS_INT( val ) )
                    &&
                    JS_GetProperty( cx, paramObj, "y", &val )
                    &&
                    ( y = JSVAL_TO_INT(val), JSVAL_IS_INT( val ) )
                    &&
                    JS_GetProperty( cx, paramObj, "image", &val )
                    &&
                    JSVAL_IS_STRING( val )
                    &&
                    ( 0 != ( sImageData = JSVAL_TO_STRING( val ) ) ) )
            {
                char const *const cImage = JS_GetStringBytes( sImageData );
                unsigned const    imageLen = JS_GetStringLength( sImageData );
                imageInfo_t imInfo ;
                if( getImageInfo( cImage, imageLen, imInfo ) ) {
                    unsigned w = imInfo.width_ ;
                    unsigned h = imInfo.height_ ;
                    if( JS_GetProperty( cx, paramObj, "w", &val ) && JSVAL_IS_INT( val ) )
                        w = JSVAL_TO_INT( val );
                    if( JS_GetProperty( cx, paramObj, "h", &val ) && JSVAL_IS_INT( val ) )
                        h = JSVAL_TO_INT( val );

                    rectangle_t r ;
                    r.xLeft_ = x ;
                    r.yTop_ = y ;
                    r.width_ = w ;
                    r.height_ = h ;

                    if( imageToPS( cImage, imageLen,
                                   r, imagePsOutput, dev ) ) {
                        *rval = JSVAL_TRUE ;
                    }
                    else
                        JS_ReportError( cx, "imageToPS: write cancelled\n" );
                }
                else
                    JS_ReportError( cx, "imageToPS: Invalid or unsupported image\n" );
            }
            else
                JS_ReportError( cx, usage );
        }
        else
            JS_ReportError( cx, usage );
    }
    else
        JS_ReportError( cx, "Invalid usblp object\n" );
    return JS_TRUE ;
}