Example #1
1
void ScreenSelector::grabColor()
{
    m_selectionRect = m_selectionRect.normalized();
    QDesktopWidget* desktop = QApplication::desktop();
    int screenNum = desktop->screenNumber(m_selectionRect.topLeft());
    QScreen* screen = QGuiApplication::screens()[screenNum];
    QPixmap screenGrab = screen->grabWindow(desktop->winId(),
        m_selectionRect.x(), m_selectionRect.y(), m_selectionRect.width(), m_selectionRect.height());
    QImage image = screenGrab.toImage();
    int numPixel = image.width() * image.height();
    int sumR = 0;
    int sumG = 0;
    int sumB = 0;

    for (int x = 0; x < image.width(); ++x) {
        for (int y = 0; y < image.height(); ++y) {
            QColor color = image.pixel(x, y);
            sumR += color.red();
            sumG += color.green();
            sumB += color.blue();
        }
    }

    QColor avgColor(sumR / numPixel, sumG / numPixel, sumB / numPixel);
    emit colorPicked(avgColor);
}
// ######################################################################
PixRGB<byte> SuperPixelRoadSegmenter::getFanAreaColor(Point2D<int> topPoint,Point2D<int> leftPoint,Point2D<int> rightPoint,
        Image<PixRGB<byte> > img)
{
    Point2D<int> p1 = topPoint;
    Point2D<int> p2 = leftPoint;
    Point2D<int> p3 = rightPoint;
    int w = img.getWidth();
    int h = img.getHeight();
    PixRGB<long> avgColor(0,0,0);
    int pixCount = 0;

    for(int y = p1.j; y < h; y++)
    {
        Point2D<int> it1 = intersectPoint(p1,p2,Point2D<int>(0,y),Point2D<int>(w,y));
        Point2D<int> it2 = intersectPoint(p1,p3,Point2D<int>(0,y),Point2D<int>(w,y));
        if(it1.i < 0) it1.i = 0;
        if(it2.i < 0) it2.i = 0;
        if(it1.i > w) it1.i = w;
        if(it2.i > w) it2.i = w;

        int length = abs(it1.i - it2.i);
        int x_init = (it1.i < it2.i) ? it1.i : it2.i;

        for(int x = x_init; x < length+x_init; x++)
        {
            if(img.coordsOk(x,y)) {
                avgColor += img.getVal(x,y);
                pixCount++;
            }
        }
    }
    if(pixCount != 0) avgColor/=pixCount;
    return (PixRGB<byte>)avgColor;

}
Example #3
0
//--------------------------------------------------------------
void ofApp::draw() {
    
	ofBackground(100, 100, 100);
	ofSetColor(255, 255, 255);
	
    kinect.draw();
	if(!kinect.isPointCloudDrawn()) {
        
        ofPushMatrix();
            ofTranslate(420, 10);
            ofScale(0.625, 0.625);
            drawContFinder();
        ofPopMatrix();
        
        // Find color of blob and draw it
        ofRectangle boundingRect;
        ofColor temp;
        if( contFinder.size() > 0) {
            for(int i=0; i<contFinder.size(); ++i){
                boundingRect = ofxCv::toOf(contFinder.getBoundingRect(i));
                if(boundingRect.getCenter().y > kinect.height * 0.5){
                    ofSetColor( (temp = avgColor(boundingRect, 0 )) );
                    ofRect(420, 320, 400, 300);
//                    cout
//                    << "r: " << (int)temp.r
//                    << " b: " << (int)temp.b
//                    << " g: " << (int)temp.g << endl;
                }
//                ofDrawBitmapString(colorNamer(temp), 420, 320); // draw name of color
            }
        }
	}

	// draw instructions
    if(bShowInfo){
        ofSetColor(255, 255, 255);
        stringstream reportStream;
    
        reportStream
        << " b to learn background."<< endl
        << " f to forget background."<< endl
        << " space to dis/enable mouse input for pointcloud"<< endl
        << " num blobs found " << contFinder.size()
        << " fps: " << ofGetFrameRate() << endl
        << " c to close connection, o to open it again, connection is: " << kinect.isConnected() << endl;
    
        ofDrawBitmapString(reportStream.str(), 20, ofGetWindowHeight()*0.75);
    }
    gui.draw();
    
}
Example #4
0
void CoronaRenderer::updateLight(std::shared_ptr<MayaObject> mobj)
{
	std::shared_ptr<mtco_MayaObject> obj(std::static_pointer_cast<mtco_MayaObject>(mobj));

	if (obj->lightShader != nullptr)
	{
		if (this->context.scene->hasLightShader(obj->lightShader))
			this->context.scene->deleteLightShader(obj->lightShader);
	}
	if (obj->removed)
		return;

	if (MayaTo::getWorldPtr()->renderType == MayaTo::MayaToWorld::WorldRenderType::IPRRENDER)
	{
		obj->transformMatrices.clear();
		obj->transformMatrices.push_back(obj->dagPath.inclusiveMatrix());
	}
	MFnDependencyNode rGlNode(getRenderGlobalsNode());
	MObject coronaGlobals = getRenderGlobalsNode();
	std::shared_ptr<RenderGlobals> renderGlobals = MayaTo::getWorldPtr()->worldRenderGlobalsPtr;
	std::shared_ptr<MayaScene> mayaScene = MayaTo::getWorldPtr()->worldScenePtr;

	MObjectArray nodeList;
	MStatus stat;

	MFnDependencyNode glFn(getRenderGlobalsNode());
	Corona::Rgb bgRgb = toCorona(getColorAttr("bgColor", glFn));
	int bgType = getEnumInt("bgType", glFn);

	MayaObject *sunLight = nullptr;

	MFnDependencyNode depFn(obj->mobject);

	if (obj->mobject.hasFn(MFn::kPointLight))
	{
		MColor col;
		getColor("color", depFn, col);
		float intensity = 1.0f;
		getFloat("intensity", depFn, intensity);
		int decay = 0;
		getEnum(MString("decayRate"), depFn, decay);
		MMatrix m = obj->transformMatrices[0] * renderGlobals->globalConversionMatrix;
		Corona::Pos LP(m[3][0], m[3][1], m[3][2]);
		PointLight *pl = new PointLight;
		pl->LP = LP;
		pl->distFactor = 1.0 / renderGlobals->scaleFactor;
		pl->lightColor = Corona::Rgb(col.r, col.g, col.b);
		pl->lightIntensity = intensity;
		getEnum(MString("decayRate"), depFn, pl->decayType);
		pl->lightRadius = getFloatAttr("lightRadius", depFn, 0.0) * renderGlobals->scaleFactor;
		pl->doShadows = getBoolAttr("useRayTraceShadows", depFn, true);
		col = getColorAttr("shadowColor", depFn);
		pl->shadowColor = Corona::Rgb(col.r, col.g, col.b);
		for (auto excludedObj : obj->excludedObjects)
		{
			pl->excludeList.nodes.push(excludedObj.get());
		}
		this->context.scene->addLightShader(pl);
		obj->lightShader = pl;
	}
	if (obj->mobject.hasFn(MFn::kSpotLight))
	{
		MVector lightDir(0, 0, -1);
		MColor col;
		getColor("color", depFn, col);
		float intensity = 1.0f;
		getFloat("intensity", depFn, intensity);
		MMatrix m = obj->transformMatrices[0] * renderGlobals->globalConversionMatrix;
		lightDir *= obj->transformMatrices[0] * renderGlobals->globalConversionMatrix;
		lightDir.normalize();
		Corona::Pos LP(m[3][0], m[3][1], m[3][2]);
		SpotLight *sl = new SpotLight;
		sl->LP = LP;
		sl->lightColor = Corona::Rgb(col.r, col.g, col.b);
		sl->lightIntensity = intensity;
		sl->LD = Corona::Dir(lightDir.x, lightDir.y, lightDir.z);
		sl->angle = 45.0f;
		sl->distFactor = 1.0 / renderGlobals->scaleFactor;
		getEnum(MString("decayRate"), depFn, sl->decayType);
		getFloat("coneAngle", depFn, sl->angle);
		getFloat("penumbraAngle", depFn, sl->penumbraAngle);
		getFloat("dropoff", depFn, sl->dropoff);
		sl->lightRadius = getFloatAttr("lightRadius", depFn, 0.0) * renderGlobals->scaleFactor;
		sl->doShadows = getBoolAttr("useRayTraceShadows", depFn, true);
		col = getColorAttr("shadowColor", depFn);
		sl->shadowColor = Corona::Rgb(col.r, col.g, col.b);
		for (auto excludedObj : obj->excludedObjects)
		{
			sl->excludeList.nodes.push(excludedObj.get());
		}
		Corona::AffineTm tm;
		setTransformationMatrix(sl->lightWorldInverseMatrix, m);
		ShadingNetwork network(obj->mobject);
		sl->lightColorMap = defineAttribute(MString("color"), depFn, network, oslRenderer);
		this->context.scene->addLightShader(sl);
		obj->lightShader = sl;
	}
	if (obj->mobject.hasFn(MFn::kDirectionalLight))
	{
		if (getBoolAttr("mtco_useAsSun", depFn, false))
		{
			if (sunLight != nullptr)
			{
				Logging::error(MString("A sun light is already defined, ignoring ") + obj->shortName);
				return;
			}
			sunLight = obj.get();
			MVector lightDir(0, 0, 1); // default dir light dir
			lightDir *= obj->transformMatrices[0];
			lightDir *= renderGlobals->globalConversionMatrix;
			lightDir.normalize();

			MColor sunColor(1);
			MFnDependencyNode sunNode(obj->mobject);
			getColor("color", sunNode, sunColor);
			sunColor *= getFloatAttr("intensity", sunNode, 1.0f);
			//float colorMultiplier colorMultiplier = getFloatAttr("mtco_sun_multiplier", sunNode, 1.0f);
			const float intensityFactor = (1.f - cos(Corona::SUN_PROJECTED_HALF_ANGLE)) / (1.f - cos(getFloatAttr("sunSizeMulti", rGlNode, 1.0f) * Corona::SUN_PROJECTED_HALF_ANGLE));
			sunColor *= intensityFactor * 1.0;// 2000000;
			Corona::Sun sun;

			Corona::ColorOrMap bgCoMap = this->context.scene->getBackground();
			SkyMap *sky = dynamic_cast<SkyMap *>(bgCoMap.getMap());
			Corona::Rgb avgColor(1, 1, 1);
			if (sky != nullptr)
			{
				avgColor = sky->sc();
			}

			Corona::Rgb sColor(sunColor.r, sunColor.g, sunColor.b);
			sun.color = sColor * avgColor;
			sun.active = true;
			sun.dirTo = Corona::Dir(lightDir.x, lightDir.y, lightDir.z).getNormalized();
			//sun.color = Corona::Rgb(sunColor.r,sunColor.g,sunColor.b);
			sun.visibleDirect = true;
			sun.visibleReflect = true;
			sun.visibleRefract = true;
			sun.sizeMultiplier = getFloatAttr("sunSizeMulti", rGlNode, 1.0);
			this->context.scene->getSun() = sun;
			if (sky != nullptr)
			{
				sky->initSky();
				this->context.scene->setBackground(bgCoMap);
				avgColor = sky->sc();
				this->context.scene->getSun().color = sColor * avgColor;
			}
		}
		else{
			MVector lightDir(0, 0, -1);
			MVector lightDirTangent(1, 0, 0);
			MVector lightDirBiTangent(0, 1, 0);
			MColor col;
			getColor("color", depFn, col);
			float intensity = 1.0f;
			getFloat("intensity", depFn, intensity);
			MMatrix m = obj->transformMatrices[0] * renderGlobals->globalConversionMatrix;
			lightDir *= m;
			lightDirTangent *= m;
			lightDirBiTangent *= m;
			lightDir.normalize();

			Corona::Pos LP(m[3][0], m[3][1], m[3][2]);
			DirectionalLight *dl = new DirectionalLight;
			dl->LP = LP;
			dl->lightColor = Corona::Rgb(col.r, col.g, col.b);
			dl->lightIntensity = intensity;
			dl->LD = Corona::Dir(lightDir.x, lightDir.y, lightDir.z);
			dl->LT = Corona::Dir(lightDirTangent.x, lightDirTangent.y, lightDirTangent.z);
			dl->LBT = Corona::Dir(lightDirBiTangent.x, lightDirBiTangent.y, lightDirBiTangent.z);
			dl->lightAngle = getFloatAttr("lightAngle", depFn, 0.0);
			dl->doShadows = getBoolAttr("useRayTraceShadows", depFn, true);
			col = getColorAttr("shadowColor", depFn);
			dl->shadowColor = Corona::Rgb(col.r, col.g, col.b);
			for (auto excludedObj : obj->excludedObjects)
			{
				dl->excludeList.nodes.push(excludedObj.get());
			}

			this->context.scene->addLightShader(dl);
			obj->lightShader = dl;
		}
	}
	if (obj->mobject.hasFn(MFn::kAreaLight))
	{
		MMatrix m = obj->transformMatrices[0] * renderGlobals->globalConversionMatrix;
		if ( obj->geom == nullptr)
			obj->geom = defineStdPlane();
		obj->geom->deleteAllInstances();

		Corona::AnimatedAffineTm atm;
		this->setAnimatedTransformationMatrix(atm, obj);
		obj->instance = obj->geom->addInstance(atm, nullptr, nullptr);
		if (getBoolAttr("mtco_envPortal", depFn, false))
		{
			Corona::EnviroPortalMtlData data;
			Corona::SharedPtr<Corona::IMaterial> mat = data.createMaterial();
			Corona::IMaterialSet ms = Corona::IMaterialSet(mat);
			obj->instance->addMaterial(ms);
		}
		else{
			Corona::NativeMtlData data;
			MColor lightColor = getColorAttr("color", depFn);
			float intensity = getFloatAttr("intensity", depFn, 1.0f);
			lightColor *= intensity;
			Corona::ColorOrMap com;
			// experimental direct corona texture
			if (getBoolAttr("mtco_noOSL", depFn, false))
			{
				MObject fileNode = getConnectedInNode(obj->mobject, "color");
				if ((fileNode != MObject::kNullObj) && (fileNode.hasFn(MFn::kFileTexture)))
				{
					MFnDependencyNode fileDep(fileNode);
					mtco_MapLoader loader(fileNode);
					Corona::SharedPtr<Corona::Abstract::Map> texmap = loader.loadBitmap("");
					com = Corona::ColorOrMap(bgRgb, texmap);
				}
			}
			else
			{
				com = defineAttribute(MString("color"), obj->mobject, oslRenderer);
				OSLMap *oslmap = (OSLMap *)com.getMap();
				if (oslmap != nullptr)
				{
					oslmap->multiplier = intensity;
				}
				else{
					Corona::Rgb col = com.getConstantColor() * intensity;
					com.setColor(col);
				}
			}

			data.emission.color = com;
			data.castsShadows = getBoolAttr("mtco_castShadows", depFn, false);

			for (auto excludedObj : obj->excludedObjects)
			{
				data.emission.excluded.nodes.push(excludedObj.get());
			}
			data.emission.disableSampling = false;
			data.emission.useTwoSidedEmission = getBoolAttr("mtco_doubleSided", depFn, false);

			Corona::SharedPtr<Corona::IMaterial> mat = data.createMaterial();
			Corona::IMaterialSet ms = Corona::IMaterialSet(mat);
			ms.visibility.direct = getBoolAttr("mtco_areaVisible", depFn, true);
			ms.visibility.reflect = getBoolAttr("mtco_visibleInReflection", depFn, true);
			ms.visibility.refract = getBoolAttr("mtco_visibleInRefraction", depFn, true);

			obj->instance->addMaterial(ms);
		}
	}
}
Example #5
0
    cv::Mat Deformation::DeformByMovingLeastSquares(const cv::Mat& inputImg, 
            const std::vector<int>& originIndex, const std::vector<int>& targetIndex)
    {
        int imgW = inputImg.cols;
        int imgH = inputImg.rows;
        cv::Size imgSize(imgW, imgH);
        cv::Mat resImg(imgSize, CV_8UC3);
        int markNum = originIndex.size() / 2;
        std::vector<double> wList(markNum);
        std::vector<MagicMath::Vector2> pHatList(markNum);
        std::vector<MagicMath::Vector2> qHatList(markNum);
        MagicMath::Vector2 pStar, qStar;
        std::vector<MagicMath::Vector2> pList(markNum);
        for (int mid = 0; mid < markNum; mid++)
        {
            pList.at(mid) = MagicMath::Vector2(originIndex.at(mid * 2), originIndex.at(mid * 2 + 1));
        }
        std::vector<MagicMath::Vector2> qList(markNum);
        for (int mid = 0; mid < markNum; mid++)
        {
            qList.at(mid) = MagicMath::Vector2(targetIndex.at(mid * 2), targetIndex.at(mid * 2 + 1));
        }
        std::vector<std::vector<double> > aMatList(markNum);
        std::vector<bool> visitFlag(imgW * imgH, 0);

        for (int hid = 0; hid < imgH; hid++)
        {
            for (int wid = 0; wid < imgW; wid++)
            {
                MagicMath::Vector2 pos(wid, hid);
                //calculate w
                bool isMarkVertex = false;
                int markedIndex = -1;
                double wSum = 0;
                for (int mid = 0; mid < markNum; mid++)
                {
                    //double dTemp = (pos - pList.at(mid)).LengthSquared(); //variable
                    double dTemp = (pos - pList.at(mid)).Length();
                    //dTemp = pow(dTemp, 1.25);
                    if (dTemp < 1.0e-15)
                    {
                        isMarkVertex = true;
                        markedIndex = mid;
                        break;
                    }
                    dTemp = pow(dTemp, 1.25);
                    wList.at(mid) = 1.0 / dTemp;
                    wSum += wList.at(mid);
                }
                //
                if (isMarkVertex)
                {
                    const unsigned char* pPixel = inputImg.ptr(hid, wid);
                    int targetH = targetIndex.at(2 * markedIndex + 1);
                    int targetW = targetIndex.at(2 * markedIndex);
                    unsigned char* pResPixel = resImg.ptr(targetH, targetW);
                    pResPixel[0] = pPixel[0];
                    pResPixel[1] = pPixel[1];
                    pResPixel[2] = pPixel[2];
                    visitFlag.at(targetH * imgW + targetW) = 1;
                }
                else
                {
                    //Calculate pStar qStar
                    pStar = MagicMath::Vector2(0.0, 0.0);
                    qStar = MagicMath::Vector2(0.0, 0.0);
                    for (int mid = 0; mid < markNum; mid++)
                    {
                        pStar += (pList.at(mid) * wList.at(mid));
                        qStar += (qList.at(mid) * wList.at(mid));
                    }
                    pStar /= wSum;
                    qStar /= wSum;

                    //Calculate pHat qHat
                    for (int mid = 0; mid < markNum; mid++)
                    {
                        pHatList.at(mid) = pList.at(mid) - pStar;
                        qHatList.at(mid) = qList.at(mid) - qStar;
                    }
                    
                    //Calculate A
                    MagicMath::Vector2 col0 = pos - pStar;
                    MagicMath::Vector2 col1(col0[1], -col0[0]);
                    for (int mid = 0; mid < markNum; mid++)
                    {
                        std::vector<double> aMat(4);
                        MagicMath::Vector2 row1(pHatList.at(mid)[1], -pHatList.at(mid)[0]);
                        aMat.at(0) = pHatList.at(mid) * col0 * wList.at(mid);
                        aMat.at(1) = pHatList.at(mid) * col1 * wList.at(mid);
                        aMat.at(2) = row1 * col0 * wList.at(mid);
                        aMat.at(3) = row1 * col1 * wList.at(mid);
                        aMatList.at(mid) = aMat;
                    }

                    //Calculate fr(v)
                    MagicMath::Vector2 fVec(0, 0);
                    for (int mid = 0; mid < markNum; mid++)
                    {
                        fVec[0] += (qHatList.at(mid)[0] * aMatList.at(mid).at(0) + qHatList.at(mid)[1] * aMatList.at(mid).at(2));
                        fVec[1] += (qHatList.at(mid)[0] * aMatList.at(mid).at(1) + qHatList.at(mid)[1] * aMatList.at(mid).at(3));
                    }

                    //Calculate target position
                    fVec.Normalise();
                    MagicMath::Vector2 targetPos = fVec * ((pos - pStar).Length()) + qStar;
                    int targetW = targetPos[0];
                    int targetH = targetPos[1];
                    if (targetH >= 0 && targetH < imgH && targetW >= 0 && targetW < imgW)
                    {
                        const unsigned char* pPixel = inputImg.ptr(hid, wid);
                        unsigned char* pResPixel = resImg.ptr(targetH, targetW);
                        pResPixel[0] = pPixel[0];
                        pResPixel[1] = pPixel[1];
                        pResPixel[2] = pPixel[2];
                        visitFlag.at(targetH * imgW + targetW) = 1;
                    }
                }
            }
        }

        std::vector<int> unVisitVecH;
        std::vector<int> unVisitVecW;
        for (int hid = 0; hid < imgH; hid++)
        {
            int baseIndex = hid * imgW;
            for (int wid = 0; wid < imgW; wid++)
            {
                if (!visitFlag.at(baseIndex + wid))
                {
                    unVisitVecH.push_back(hid);
                    unVisitVecW.push_back(wid);
                }
            }
        }
        int minAcceptSize = 4;
        int fillTime = 1;
        while (unVisitVecH.size() > 0)
        {
            DebugLog << "unVisit number: " << unVisitVecH.size() << std::endl;
            std::vector<int> unVisitVecHCopy = unVisitVecH;
            std::vector<int> unVisitVecWCopy = unVisitVecW;
            unVisitVecH.clear();
            unVisitVecW.clear();
            int unVisitSize = unVisitVecHCopy.size();
            for (int uid = 0; uid < unVisitSize; uid++)
            {
                MagicMath::Vector3 avgColor(0, 0, 0);
                int hid = unVisitVecHCopy.at(uid);
                int wid = unVisitVecWCopy.at(uid);
                int avgSize = 0;
                if ((hid - 1) >= 0 && visitFlag.at((hid - 1) * imgW + wid))
                {
                    unsigned char* pPixel = resImg.ptr(hid - 1, wid);
                    avgColor[0] += pPixel[0];
                    avgColor[1] += pPixel[1];
                    avgColor[2] += pPixel[2];
                    avgSize++;
                }
                if ((hid + 1) < imgH && visitFlag.at((hid + 1) * imgW + wid))
                {
                    unsigned char* pPixel = resImg.ptr(hid + 1, wid);
                    avgColor[0] += pPixel[0];
                    avgColor[1] += pPixel[1];
                    avgColor[2] += pPixel[2];
                    avgSize++;
                }
                if ((wid - 1) >= 0 && visitFlag.at(hid * imgW + wid - 1))
                {
                    unsigned char* pPixel = resImg.ptr(hid, wid - 1);
                    avgColor[0] += pPixel[0];
                    avgColor[1] += pPixel[1];
                    avgColor[2] += pPixel[2];
                    avgSize++;
                }
                if ((wid + 1) < imgW && visitFlag.at(hid * imgW + wid + 1))
                {
                    unsigned char* pPixel = resImg.ptr(hid, wid + 1);
                    avgColor[0] += pPixel[0];
                    avgColor[1] += pPixel[1];
                    avgColor[2] += pPixel[2];
                    avgSize++;
                }
                if (avgSize >= minAcceptSize)
                {
                    visitFlag.at(hid * imgW + wid) = 1;
                    avgColor /= avgSize;
                    unsigned char* pFillPixel = resImg.ptr(hid, wid);
                    pFillPixel[0] = avgColor[0];
                    pFillPixel[1] = avgColor[1];
                    pFillPixel[2] = avgColor[2];
                }
                else
                {
                    unVisitVecH.push_back(hid);
                    unVisitVecW.push_back(wid);
                }
            }
            if (fillTime == 4)
            {
                minAcceptSize--;
            }
            else if (fillTime == 6)
            {
                minAcceptSize--;
            }
            else if (fillTime == 8)
            {
                minAcceptSize--;
            }
            fillTime++;
        }
        //fill hole
        /*for (int hid = 0; hid < imgH; hid++)
        {
            int baseIndex = hid * imgW;
            for (int wid = 0; wid < imgW; wid++)
            {
                if (!visitFlag.at(baseIndex + wid))
                {
                    double wSum = 0;
                    MagicMath::Vector3 avgColor(0, 0, 0);
                    for (int wRight = wid + 1; wRight < imgW; wRight++)
                    {
                        if (visitFlag.at(baseIndex + wRight))
                        {
                            double wTemp = 1.0 / (wRight - wid);
                            wSum += wTemp;
                            unsigned char* pPixel = resImg.ptr(hid, wRight);
                            avgColor[0] += wTemp * pPixel[0];
                            avgColor[1] += wTemp * pPixel[1];
                            avgColor[2] += wTemp * pPixel[2];
                            break;
                        }
                    }
                    for (int wLeft = wid - 1; wLeft >= 0; wLeft--)
                    {
                        if (visitFlag.at(baseIndex + wLeft))
                        {
                            double wTemp = 1.0 / (wid - wLeft);
                            wSum += wTemp;
                            unsigned char* pPixel = resImg.ptr(hid, wLeft);
                            avgColor[0] += wTemp * pPixel[0];
                            avgColor[1] += wTemp * pPixel[1];
                            avgColor[2] += wTemp * pPixel[2];
                            break;
                        }
                    }
                    for (int hUp = hid - 1; hUp >= 0; hUp--)
                    {
                        if (visitFlag.at(hUp * imgW + wid))
                        {
                            double wTemp = 1.0 / (hid - hUp);
                            unsigned char* pPixel = resImg.ptr(hUp, wid);
                            wSum += wTemp;
                            avgColor[0] += wTemp * pPixel[0];
                            avgColor[1] += wTemp * pPixel[1];
                            avgColor[2] += wTemp * pPixel[2];
                            break;
                        }
                    }
                    for (int hDown = hid + 1; hDown < imgH; hDown++)
                    {
                        if (visitFlag.at(hDown * imgW + wid))
                        {
                            double wTemp = 1.0 / (hDown - hid);
                            unsigned char* pPixel = resImg.ptr(hDown, wid);
                            wSum += wTemp;
                            avgColor[0] += wTemp * pPixel[0];
                            avgColor[1] += wTemp * pPixel[1];
                            avgColor[2] += wTemp * pPixel[2];
                            break;
                        }
                    }
                    if (wSum > 1.0e-15)
                    {
                        avgColor /= wSum;
                    }
                    unsigned char* pFillPixel = resImg.ptr(hid, wid);
                    pFillPixel[0] = avgColor[0];
                    pFillPixel[1] = avgColor[1];
                    pFillPixel[2] = avgColor[2];
                }
            }
        }*/
        return resImg;
    }
Example #6
0
// ######################################################################
//img : input image in RGB space
//K   : number of groups create by kmean
//dist: distance weight when doing the segment, higher weight will make
//      each region group by its neighbor pixel
// ######################################################################
Image<PixRGB<byte> > getKMeans(Image<PixRGB<byte> > img,int K,float dist)
{
  //convert iNVT image to cvImage
  IplImage *cvImg = img2ipl(img);

  int h = img.getHeight();
  int w = img.getWidth();
  LINFO("Image Width %d Height %d cv W %d,H %d",w,h,cvImg->width,cvImg->height);
  CvMat *sample  = cvCreateMat(w*h, 1, CV_32FC(5));   
  //CvMat *sample  = cvCreateMat(w*h, 1, CV_32FC(3));   
  CvMat *cluster = cvCreateMat(w*h, 1, CV_32SC1);   
  for(int y = 0; y < h; y++)
    { 
      for(int x = 0; x < w; x++)
        {     
          int idx= y*w+x;   
          int idxpix= y*w*3+x*3;   
          MAT_ELEM(sample,idx,0,0,x*dist);   
          MAT_ELEM(sample,idx,0,1,y*dist);   
          MAT_ELEM(sample,idx,0,2, *(cvImg->imageData + idxpix + 0));
          MAT_ELEM(sample,idx,0,3, *(cvImg->imageData + idxpix + 1));
          MAT_ELEM(sample,idx,0,4, *(cvImg->imageData + idxpix + 2));
        }   
    }   

  //Doing cvKmean
  cvKMeans2(sample, K, cluster,
            cvTermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER,
                           TT_KMEANS_ITERATIONS, TT_KMEANS_PRECISION)) ;

  IplImage 	*dst = cvCreateImage(cvGetSize(cvImg),8,3);   
  cvZero(dst);   

  std::vector<std::vector<Point2D<int> > >  groups;
  groups.resize(K);

  // Put Pixel Color to each labeled bin
  for(int y = 0; y < h; y++)
    {   
      for(int x = 0; x < w; x++)
        {   
          int idx = cluster->data.i[y*w+x];   
          groups[idx].push_back(Point2D<int>(x,y));
        }   
    }
   
  // Given a int label map, we will create a average color map
  Image<PixRGB<byte> > output(img.getDims(), ZEROS);

  //Compute avg color for each region
  for(size_t grpIdx=0; grpIdx < groups.size(); grpIdx++)
    {
      //Compute Average Color
      PixRGB<long> avgColor(0,0,0);
      for(size_t pntIdx=0; pntIdx<groups[grpIdx].size(); pntIdx++)
        avgColor +=  img.getVal(groups[grpIdx][pntIdx]);

      if(groups[grpIdx].size() != 0)
        avgColor /= groups[grpIdx].size();

      //Asign avg color to region pixels
      for(size_t pntIdx=0; pntIdx<groups[grpIdx].size(); pntIdx++)
        output.setVal(groups[grpIdx][pntIdx],avgColor);
    }

  cvReleaseMat(&sample);   
  cvReleaseMat(&cluster);         
  cvReleaseImage(&cvImg);  
  return output;	
}