Spectrum IGIIntegrator::Li(const Scene &scene, const Renderer *renderer, const RayDifferential &ray, const Intersection &isect, const Sample *sample, RNG &rng, MemoryArena &arena) const { Spectrum L(0.); Vector wo = -ray.d; // Compute emitted light if ray hit an area light source L += isect.Le(wo); // Evaluate BSDF at hit point BSDF *bsdf = isect.GetBSDF(ray, arena); const Point &p = bsdf->dgShading.p; const Normal &n = bsdf->dgShading.nn; L += UniformSampleAllLights(scene, renderer, arena, p, n, wo, isect.rayEpsilon, ray.time, bsdf, sample, rng, lightSampleOffsets, bsdfSampleOffsets); // Compute indirect illumination with virtual lights uint32_t lSet = min(uint32_t(sample->oneD[vlSetOffset][0] * nLightSets), nLightSets-1); for (uint32_t i = 0; i < virtualLights[lSet].size(); ++i) { const VirtualLight &vl = virtualLights[lSet][i]; // Compute virtual light's tentative contribution _Llight_ float d2 = DistanceSquared(p, vl.p); Vector wi = Normalize(vl.p - p); float G = AbsDot(wi, n) * AbsDot(wi, vl.n) / d2; G = min(G, gLimit); Spectrum f = bsdf->f(wo, wi); if (G == 0.f || f.IsBlack()) continue; Spectrum Llight = f * G * vl.pathContrib / nLightPaths; RayDifferential connectRay(p, wi, ray, isect.rayEpsilon, sqrtf(d2) * (1.f - vl.rayEpsilon)); Llight *= renderer->Transmittance(scene, connectRay, NULL, rng, arena); // Possibly skip virtual light shadow ray with Russian roulette if (Llight.y() < rrThreshold) { float continueProbability = .1f; if (rng.RandomFloat() > continueProbability) continue; Llight /= continueProbability; } // Add contribution from _VirtualLight_ _vl_ if (!scene.IntersectP(connectRay)) L += Llight; } if (ray.depth < maxSpecularDepth) { // Do bias compensation for bounding geometry term int nSamples = (ray.depth == 0) ? nGatherSamples : 1; for (int i = 0; i < nSamples; ++i) { Vector wi; float pdf; BSDFSample bsdfSample = (ray.depth == 0) ? BSDFSample(sample, gatherSampleOffset, i) : BSDFSample(rng); Spectrum f = bsdf->Sample_f(wo, &wi, bsdfSample, &pdf, BxDFType(BSDF_ALL & ~BSDF_SPECULAR)); if (!f.IsBlack() && pdf > 0.f) { // Trace ray for bias compensation gather sample float maxDist = sqrtf(AbsDot(wi, n) / gLimit); RayDifferential gatherRay(p, wi, ray, isect.rayEpsilon, maxDist); Intersection gatherIsect; Spectrum Li = renderer->Li(scene, gatherRay, sample, rng, arena, &gatherIsect); if (Li.IsBlack()) continue; // Add bias compensation ray contribution to radiance sum float Ggather = AbsDot(wi, n) * AbsDot(-wi, gatherIsect.dg.nn) / DistanceSquared(p, gatherIsect.dg.p); if (Ggather - gLimit > 0.f && !isinf(Ggather)) { float gs = (Ggather - gLimit) / Ggather; L += f * Li * (AbsDot(wi, n) * gs / (nSamples * pdf)); } } } } if (ray.depth + 1 < maxSpecularDepth) { Vector wi; // Trace rays for specular reflection and refraction L += SpecularReflect(ray, bsdf, rng, isect, renderer, scene, sample, arena); L += SpecularTransmit(ray, bsdf, rng, isect, renderer, scene, sample, arena); } return L; }
int main() { cv::Mat src; cv::Mat dst; cv::Mat paintable; int end=false; // read the img src = imread("C:/Users/giki/Pictures/quadri_dataset/quadro_tre.jpg", 1); if (src.empty()) return -1; cv::Size s = src.size(); src.copyTo(paintable); // Convert to grayscale cv::Mat gray; cv::cvtColor(src, gray, CV_BGR2GRAY); // Convert to binary image using Canny cv::Mat bw; cv::Canny(gray, bw, 0, 50, 5); // Find contours std::vector<std::vector<cv::Point> > contours; cv::findContours(bw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); vector<Vec4i> hierarchy; // The array for storing the approximation curve std::vector<cv::Point> approx; // Rects extraction vector<vector<Point>> contours_poly( contours.size() ); vector<Rect> bound_rect( contours.size() ); vector<vector<Rect>> good_rect; int good_rect_index=0; for (int i = 0; i < contours.size(); i++) { // poligon approximation approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); // extraciont only poligon=rect bound_rect[i] = boundingRect( Mat(contours_poly[i]) ); //------------- if (bound_rect[i].area() > (s.area()*0.30) ) { vector<Rect> vector; vector.push_back(bound_rect[i]); good_rect.push_back(vector); // estrapolo tutti i rettangoli buoni good_rect_index++; Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); rectangle( paintable, bound_rect[i].tl(), bound_rect[i].br(), color, 2, 8, 0 ); } } if (good_rect.size()==0) // non si sono trovati rettangoli compatibili, forse // l'immagine è una parte interna di quadro { dst=src; end=true; } //cv::imshow("src", paintable); //waitKey(); if (end==false) { // adesso di questi rettangoli buoni devo prendere quelli che effettivamente costituiscono il mio quadro for (int j = 0; j < good_rect_index; j++) { Rect confront = good_rect[j][0]; int x_center = confront.x+confront.width/2; int y_center = confront.y+confront.height/2; for (int i = 0; i < good_rect_index; i++) { if (j==i) continue; else if (x_center > good_rect[i][0].x + good_rect[i][0].width/2 - good_rect[i][0].width*0.05) if (x_center < good_rect[i][0].x + good_rect[i][0].width/2+good_rect[i][0].width*0.05) if (y_center > good_rect[i][0].y+good_rect[i][0].height/2-good_rect[i][0].height*0.05) if (y_center < good_rect[i][0].y+good_rect[i][0].height/2+good_rect[i][0].height*0.05) good_rect[i].push_back(confront); }// sto codicione che andrà semplificato praticamente controlla il centro dei rettangoli e definisce // due rettangoli come buoni se hanno lo stesso centro (con un minimo di errore accettabile) // infatti ho deciso che per me un quadro è una successione di rettangoli con lo stesso centro // (cornice interna + cornice esterna + inizio tela = 3 rettangoli con lo stesso centro), // più o meno funziona sempre, a meno di cornici strane. } // Ho un vettore di vettori contenente tutti gli accoppiamenti, prendo l'accoppiamento che // contiene i rettangoli più grandi vector<Rect> quadro; for( int i = 0; i< good_rect_index; i++ ) // iterate through each contour. { if (i==0) quadro=good_rect[i]; else if (quadro.size() < good_rect[i].size()) { quadro=good_rect[i]; } } int size = quadro.size(); for (int i=0; i < size; i++) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); rectangle( paintable, quadro[i].tl(), quadro[i].br(), color, 2, 8, 0 ); } // Max rect extraction from the quadro int largest_contour_index=0; cv::Rect big_rect; // The variable to store max rect for( int i = 0; i < quadro.size(); i++ ) // iterate through each contour. { if (i==0) big_rect=quadro[i]; else if (big_rect.area() < quadro[i].area()) { big_rect=quadro[i]; largest_contour_index=i; } } // cut the image to have only the quadro src(big_rect).copyTo(dst); } cv::imshow("src", src); cv::imshow("src_with rect", paintable); cv::imshow("dst", dst); waitKey(); return 0; }
// Reproduce mates & mutates the individuals of the species // It may access the global species list in the population // because some babies may turn out to belong in another species // that have to be created. // Also calls Birth() for every new baby void Species::Reproduce(Population &a_Pop, Parameters& a_Parameters, RNG& a_RNG) { Genome t_baby; // temp genome for reproduction int t_offspring_count = Rounded(GetOffspringRqd()); // no offspring?! yikes.. dead species! if (t_offspring_count == 0) { // maybe do something else? return; } ////////////////////////// // Reproduction // Spawn t_offspring_count babies bool t_champ_chosen = false; bool t_baby_exists_in_pop = false; while(t_offspring_count--) { // if the champ was not chosen, do it now.. if (!t_champ_chosen) { t_baby = m_Individuals[0]; t_champ_chosen = true; } // or if it was, then proceed with the others else { do // - while the baby already exists somewhere in the new population { // this tells us if the baby is a result of mating bool t_mated = false; // There must be individuals there.. ASSERT(NumIndividuals() > 0); // for a species of size 1 we can only mutate // NOTE: but does it make sense since we know this is the champ? if (NumIndividuals() == 1) { t_baby = GetIndividual(a_Parameters, a_RNG); t_mated = false; } // else we can mate else { do // keep trying to mate until a good offspring is produced { Genome t_mom = GetIndividual(a_Parameters, a_RNG); // choose whether to mate at all // Do not allow crossover when in simplifying phase if ((a_RNG.RandFloat() < a_Parameters.CrossoverRate) && (a_Pop.GetSearchMode() != SIMPLIFYING)) { // get the father Genome t_dad; bool t_interspecies = false; // There is a probability that the father may come from another species if ((a_RNG.RandFloat() < a_Parameters.InterspeciesCrossoverRate) && (a_Pop.m_Species.size()>1)) { // Find different species (random one) // !!!!!!!!!!!!!!!!! int t_diffspec = a_RNG.RandInt(0, static_cast<int>(a_Pop.m_Species.size()-1)); t_dad = a_Pop.m_Species[t_diffspec].GetIndividual(a_Parameters, a_RNG); t_interspecies = true; } else { // Mate within species t_dad = GetIndividual(a_Parameters, a_RNG); // The other parent should be a different one // number of tries to find different parent int t_tries = 32; if (!a_Parameters.AllowClones) while(((t_mom.GetID() == t_dad.GetID()) || (t_mom.CompatibilityDistance(t_dad, a_Parameters) < 0.00001) ) && (t_tries--)) { t_dad = GetIndividual(a_Parameters, a_RNG); } else while(((t_mom.GetID() == t_dad.GetID()) ) && (t_tries--)) { t_dad = GetIndividual(a_Parameters, a_RNG); } t_interspecies = false; } // OK we have both mom and dad so mate them // Choose randomly one of two types of crossover if (a_RNG.RandFloat() < a_Parameters.MultipointCrossoverRate) { t_baby = t_mom.Mate( t_dad, false, t_interspecies, a_RNG); } else { t_baby = t_mom.Mate( t_dad, true, t_interspecies, a_RNG); } t_mated = true; } // don't mate - reproduce the mother asexually else { t_baby = t_mom; t_mated = false; } } while (t_baby.HasDeadEnds() || (t_baby.NumLinks() == 0)); // in case of dead ends after crossover we will repeat crossover // until it works } // Mutate the baby if ((!t_mated) || (a_RNG.RandFloat() < a_Parameters.OverallMutationRate)) MutateGenome(t_baby_exists_in_pop, a_Pop, t_baby, a_Parameters, a_RNG); // Check if this baby is already present somewhere in the offspring // we don't want that t_baby_exists_in_pop = false; // Unless of course, we want if (!a_Parameters.AllowClones) { for(unsigned int i=0; i<a_Pop.m_TempSpecies.size(); i++) { for(unsigned int j=0; j<a_Pop.m_TempSpecies[i].m_Individuals.size(); j++) { if ( (t_baby.CompatibilityDistance(a_Pop.m_TempSpecies[i].m_Individuals[j], a_Parameters) < 0.00001) // identical genome? ) { t_baby_exists_in_pop = true; break; } } } } } while (t_baby_exists_in_pop); // end do } // Final place to test for problems // If there is anything wrong here, we will just // pick a random individual and leave him unchanged if ((t_baby.NumLinks() == 0) || t_baby.HasDeadEnds()) { t_baby = GetIndividual(a_Parameters, a_RNG); } // We have a new offspring now // give the offspring a new ID t_baby.SetID(a_Pop.GetNextGenomeID()); a_Pop.IncrementNextGenomeID(); // sort the baby's genes t_baby.SortGenes(); // clear the baby's fitness t_baby.SetFitness(0); t_baby.SetAdjFitness(0); t_baby.SetOffspringAmount(0); t_baby.ResetEvaluated(); ////////////////////////////////// // put the baby to its species // ////////////////////////////////// // before Reproduce() is invoked, it is assumed that a // clone of the population exists with the name of m_TempSpecies // we will store results there. // after all reproduction completes, the original species will be replaced back bool t_found = false; std::vector<Species>::iterator t_cur_species = a_Pop.m_TempSpecies.begin(); // No species yet? if (t_cur_species == a_Pop.m_TempSpecies.end()) { // create the first species and place the baby there a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID())); a_Pop.IncrementNextSpeciesID(); } else { // try to find a compatible species Genome t_to_compare = t_cur_species->GetRepresentative(); t_found = false; while((t_cur_species != a_Pop.m_TempSpecies.end()) && (!t_found)) { if (t_baby.IsCompatibleWith( t_to_compare, a_Parameters)) { // found a compatible species t_cur_species->AddIndividual(t_baby); t_found = true; // the search is over } else { // keep searching for a matching species t_cur_species++; if (t_cur_species != a_Pop.m_TempSpecies.end()) { t_to_compare = t_cur_species->GetRepresentative(); } } } // if couldn't find a match, make a new species if (!t_found) { a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID())); a_Pop.IncrementNextSpeciesID(); } } } }
double operator()(Individual& ind, RNG& rng, EA& ea) { int max_x = get<X_SIZE>(ea,10); int max_y = get<Y_SIZE>(ea,10); int grid_size = max_x * max_y; vector<int> agent_pos (grid_size, -1); vector<int> exec_order (grid_size); double f=0.0; // get the "prototype" phenotype (markov network): typename EA::phenotype_type &N = ealib::phenotype(ind, ea); vector<typename EA::phenotype_type> as; // for (int q=0; q<get<NUM_START_AGENTS>(ea,1); q++) { as.push_back(N); //grid_size, N); // my agents or networks agent_pos[q] = q; as[q].reset(rng.seed()); } for (int i=0; i<grid_size; ++i) { exec_order[i] = i; } std::vector< std::vector<int> > cell_color(grid_size, std::vector<int>(2, 0)); std::vector<int> apop_count(grid_size,0); update_world_stigmergic_communication_apop_N(get<WORLD_UPDATES>(ea,10), agent_pos, exec_order, as, cell_color, apop_count, ind, rng, ea); int fit_func = get<BODYPLAN>(ea,0) ; switch(fit_func) { case 0: f = body_plan0(grid_size, max_x, max_y, agent_pos, as, ea); break; case 1: f = body_plan1(grid_size, max_x, max_y, agent_pos, as, ea); break; case 2: f = body_plan2(grid_size, max_x, max_y, agent_pos, as, ea); break; case 3: f = body_plan3(grid_size, max_x, max_y, agent_pos, as, ea); break; case 4: f = body_plan4(grid_size, max_x, max_y, agent_pos, as, ea); break; case 5: f = body_plan5(grid_size, max_x, max_y, agent_pos, as, ea); break; case 6: f = body_plan6(grid_size, max_x, max_y, agent_pos, as, ea); break; case 7: f = body_plan7(grid_size, max_x, max_y, agent_pos, as, ea); break; case 8: f = body_plan8(grid_size, max_x, max_y, agent_pos, as, ea); break; case 9: f = body_plan9(grid_size, max_x, max_y, agent_pos, as, ea); break; case 10: f = body_plan10(grid_size, max_x, max_y, agent_pos, as, ea); break; case 11: f = body_plan11(grid_size, max_x, max_y, agent_pos, as, ea); break; case 12: f = body_plan12(grid_size, max_x, max_y, agent_pos, as, ea); break; case 13: f = body_plan13(grid_size, max_x, max_y, agent_pos, as, ea); break; case 14: f = body_plan14(grid_size, max_x, max_y, agent_pos, as, ea); break; case 15: f = body_plan15(grid_size, max_x, max_y, agent_pos, as, ea); break; case 16: f = body_plan16(grid_size, max_x, max_y, agent_pos, as, ea); break; case 17: f = body_plan17(grid_size, max_x, max_y, agent_pos, as, ea); break; case 18: f = body_plan18(grid_size, max_x, max_y, agent_pos, as, ea); break; case 19: f = body_plan19(grid_size, max_x, max_y, agent_pos, as, ea); break; } if (f == 0) { f = 1; } return (f); }
bool ompl::geometric::pSBL::checkSolution(RNG &rng, bool start, TreeData &tree, TreeData &otherTree, Motion *motion, std::vector<Motion*> &solution) { Grid<MotionInfo>::Coord coord; projectionEvaluator_->computeCoordinates(motion->state, coord); otherTree.lock.lock(); Grid<MotionInfo>::Cell* cell = otherTree.grid.getCell(coord); if (cell && !cell->data.empty()) { Motion *connectOther = cell->data[rng.uniformInt(0, cell->data.size() - 1)]; otherTree.lock.unlock(); if (pdef_->getGoal()->isStartGoalPairValid(start ? motion->root : connectOther->root, start ? connectOther->root : motion->root)) { Motion *connect = new Motion(si_); si_->copyState(connect->state, connectOther->state); connect->parent = motion; connect->root = motion->root; motion->lock.lock(); motion->children.push_back(connect); motion->lock.unlock(); addMotion(tree, connect); if (isPathValid(tree, connect) && isPathValid(otherTree, connectOther)) { if (start) connectionPoint_ = std::make_pair(motion->state, connectOther->state); else connectionPoint_ = std::make_pair(connectOther->state, motion->state); /* extract the motions and put them in solution vector */ std::vector<Motion*> mpath1; while (motion != nullptr) { mpath1.push_back(motion); motion = motion->parent; } std::vector<Motion*> mpath2; while (connectOther != nullptr) { mpath2.push_back(connectOther); connectOther = connectOther->parent; } if (!start) mpath1.swap(mpath2); for (int i = mpath1.size() - 1 ; i >= 0 ; --i) solution.push_back(mpath1[i]); solution.insert(solution.end(), mpath2.begin(), mpath2.end()); return true; } } } else otherTree.lock.unlock(); return false; }
void RSATests::testSigningVerifying() { AsymmetricKeyPair* kp; RSAParameters p; // Public exponents to test std::vector<ByteString> exponents; exponents.push_back("010001"); exponents.push_back("03"); exponents.push_back("0B"); exponents.push_back("11"); // Key sizes to test std::vector<size_t> keySizes; keySizes.push_back(1024); keySizes.push_back(1280); keySizes.push_back(2048); //keySizes.push_back(4096); // Mechanisms to test std::vector<AsymMech::Type> mechanisms; #ifndef WITH_FIPS mechanisms.push_back(AsymMech::RSA_MD5_PKCS); #endif mechanisms.push_back(AsymMech::RSA_SHA1_PKCS); mechanisms.push_back(AsymMech::RSA_SHA224_PKCS); mechanisms.push_back(AsymMech::RSA_SHA256_PKCS); mechanisms.push_back(AsymMech::RSA_SHA384_PKCS); mechanisms.push_back(AsymMech::RSA_SHA512_PKCS); mechanisms.push_back(AsymMech::RSA_SHA1_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA224_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA256_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA384_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA512_PKCS_PSS); #ifndef WITH_FIPS mechanisms.push_back(AsymMech::RSA_SSL); #endif /* Max salt length for SHA512 and 1024-bit RSA is 62 bytes */ RSA_PKCS_PSS_PARAMS pssParams[] = { { HashAlgo::SHA1, AsymRSAMGF::MGF1_SHA1, 20 }, { HashAlgo::SHA224, AsymRSAMGF::MGF1_SHA224, 0 }, { HashAlgo::SHA256, AsymRSAMGF::MGF1_SHA256, 0 }, { HashAlgo::SHA384, AsymRSAMGF::MGF1_SHA384, 48 }, { HashAlgo::SHA512, AsymRSAMGF::MGF1_SHA512, 62 } }; for (std::vector<ByteString>::iterator e = exponents.begin(); e != exponents.end(); e++) { for (std::vector<size_t>::iterator k = keySizes.begin(); k != keySizes.end(); k++) { p.setE(*e); p.setBitLength(*k); // Generate key-pair CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Test mechanisms that perform internal hashing for (std::vector<AsymMech::Type>::iterator m = mechanisms.begin(); m != mechanisms.end(); m++) { ByteString blockSignature, singlePartSignature; void* param = NULL; size_t paramLen = 0; bool isPSS = false; switch (*m) { case AsymMech::RSA_SHA1_PKCS_PSS: param = &pssParams[0]; paramLen = sizeof(pssParams[0]); isPSS = true; break; case AsymMech::RSA_SHA224_PKCS_PSS: param = &pssParams[1]; paramLen = sizeof(pssParams[1]); isPSS = true; break; case AsymMech::RSA_SHA256_PKCS_PSS: param = &pssParams[2]; paramLen = sizeof(pssParams[2]); isPSS = true; break; case AsymMech::RSA_SHA384_PKCS_PSS: param = &pssParams[3]; paramLen = sizeof(pssParams[3]); isPSS = true; break; case AsymMech::RSA_SHA512_PKCS_PSS: param = &pssParams[4]; paramLen = sizeof(pssParams[4]); isPSS = true; break; default: break; } // Sign the data in blocks CPPUNIT_ASSERT(rsa->signInit(kp->getPrivateKey(), *m, param, paramLen)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(0, 134))); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(134, 289))); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(134 + 289))); CPPUNIT_ASSERT(rsa->signFinal(blockSignature)); // Sign the data in one pass CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, singlePartSignature, *m, param, paramLen)); // If it is not a PSS signature, check if the two signatures match if (!isPSS) { // Check if the two signatures match CPPUNIT_ASSERT(blockSignature == singlePartSignature); } // Now perform multi-pass verification CPPUNIT_ASSERT(rsa->verifyInit(kp->getPublicKey(), *m, param, paramLen)); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(0, 125))); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(125, 247))); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(125 + 247))); CPPUNIT_ASSERT(rsa->verifyFinal(blockSignature)); // And single-pass verification CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, singlePartSignature, *m, param, paramLen)); } // Test mechanisms that do not perform internal hashing // Test PKCS #1 signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 35)); // Sign the data ByteString signature; CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS)); // Verify the signature CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS)); // Test raw RSA signing size_t byteSize = *k >> 3; CPPUNIT_ASSERT(rng->generateRandom(dataToSign, byteSize)); // Strip the topmost bit dataToSign[0] &= 0x7F; // Sign the data CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA)); // Verify the signature CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA)); #ifdef WITH_RAW_PSS // Test raw (SHA1) PKCS PSS signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 20)); CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[0], sizeof(pssParams[0]))); CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[0], sizeof(pssParams[0]))); // Test raw (SHA224) PKCS PSS signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 28)); CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[1], sizeof(pssParams[1]))); CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[1], sizeof(pssParams[1]))); // Test raw (SHA256) PKCS PSS signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 32)); CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[2], sizeof(pssParams[2]))); CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[2], sizeof(pssParams[2]))); // Test raw (SHA384) PKCS PSS signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 48)); CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[3], sizeof(pssParams[3]))); CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[3], sizeof(pssParams[3]))); // Test raw (SHA512) PKCS PSS signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 64)); CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[4], sizeof(pssParams[4]))); CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS_PSS, &pssParams[4], sizeof(pssParams[4]))); #endif rsa->recycleKeyPair(kp); } } }
Spectrum VolumePatIntegrator::Li_Single(const Scene *scene, const Renderer *renderer, const RayDifferential &ray, const Sample *sample, RNG &rng, Spectrum *T, MemoryArena &arena) const { VolumeRegion *vr = scene->volumeRegion; float t0, t1; if (!vr || !vr->IntersectP(ray, &t0, &t1) || (t1-t0) == 0.f) { *T = 1.f; return 0.f; } // Do single scattering volume integration in _vr_ Spectrum Lv(0.); // Prepare for volume integration stepping int nSamples = Ceil2Int((t1-t0) / stepSize); float step = (t1 - t0) / nSamples; Spectrum Tr(1.f); Point p = ray(t0), pPrev; Vector w = -ray.d; t0 += sample->oneD[scatterSampleOffset][0] * step; // Compute sample patterns for single scattering samples float *lightNum = arena.Alloc<float>(nSamples); LDShuffleScrambled1D(1, nSamples, lightNum, rng); float *lightComp = arena.Alloc<float>(nSamples); LDShuffleScrambled1D(1, nSamples, lightComp, rng); float *lightPos = arena.Alloc<float>(2*nSamples); LDShuffleScrambled2D(1, nSamples, lightPos, rng); uint32_t sampOffset = 0; for (int i = 0; i < nSamples; ++i, t0 += step) { // Advance to sample at _t0_ and update _T_ pPrev = p; p = ray(t0); Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, ray.time, ray.depth); Spectrum stepTau = vr->tau(tauRay, .5f * stepSize, rng.RandomFloat()); Tr *= Exp(-stepTau); // Possibly terminate ray marching if transmittance is small if (Tr.y() < 1e-3) { const float continueProb = .5f; if (rng.RandomFloat() > continueProb) { Tr = 0.f; break; } Tr /= continueProb; } // Compute single-scattering source term at _p_ Lv += Tr * vr->Lve(p, w, ray.time); Spectrum ss = vr->Sigma_s(p, w, ray.time); if (!ss.IsBlack() && scene->lights.size() > 0) { int nLights = scene->lights.size(); int ln = min(Floor2Int(lightNum[sampOffset] * nLights), nLights-1); Light *light = scene->lights[ln]; // Add contribution of _light_ due to scattering at _p_ float pdf; VisibilityTester vis; Vector wo; LightSample ls(lightComp[sampOffset], lightPos[2*sampOffset], lightPos[2*sampOffset+1]); Spectrum L = light->Sample_L(p, 0.f, ls, ray.time, &wo, &pdf, &vis); if (!L.IsBlack() && pdf > 0.f && vis.Unoccluded(scene)) { Spectrum Ld = L * vis.Transmittance(scene, renderer, NULL, rng, arena); Lv += Tr * ss * vr->p(p, w, -wo, ray.time) * Ld * float(nLights) / pdf; } } ++sampOffset; } *T = Tr; return Lv * step; }
//This function is called everytime a new image is published void imageCallback(const sensor_msgs::ImageConstPtr& original_image) { bpMsgs::brick brick; brick.header.stamp.sec = original_image->header.stamp.sec; brick.header.stamp.nsec = original_image->header.stamp.nsec; ROS_INFO("stamp sec: %ld nano: %ld", (long int)original_image->header.stamp.sec, (long int)original_image->header.stamp.nsec); cv::namedWindow("trackBar", CV_WINDOW_NORMAL); cv::resizeWindow("trackBar", 400, 300); createTrackbar( "highThresh", "trackBar", &low_thresh, max_thresh, callback ); createTrackbar( "lowThresh", "trackBar", &high_thresh, max_thresh, callback); //Convert from the ROS image message to a CvImage suitable for working with OpenCV for processing cv_bridge::CvImagePtr cv_ptr; try { //Always copy, returning a mutable CvImage //OpenCV expects color images to use BGR channel order. cv_ptr = cv_bridge::toCvCopy(original_image, enc::BGR8); } catch (cv_bridge::Exception& e) { //if there is an error during conversion, display it ROS_ERROR("camera::main.cpp::cv_bridge exception: %s", e.what()); return; } Mat imgdest; HSVToBW(cv_ptr->image,imgdest,2); //filter(imgdest); //erode(imgdest,imgdest,Size(3,3),Point(0,0),3); //erode(imgdest,imgdest,Mat(),Point(-1,-1),3); GaussianBlur(imgdest, imgdest, Size(3,3), 1.5, 1.5); cv::imshow("grey", imgdest); Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; double area; int k; /// Detect edges using canny //Canny( src_gray, canny_output, 400, 1000, 3 ); //imshow( "After Canny", canny_output ); /// Find contours findContours( /*canny_output*/ imgdest, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, Point(0, 0) ); vector<Moments> _mu(contours.size()); vector<Point2f> _mc(contours.size()); vector<double> _ma(contours.size()); vector<RotatedRect> minRect( contours.size() ); // vector<RotatedRect> minEllipse( contours.size() ); for( int i = 0; i < contours.size(); i++) { minRect[i] = minAreaRect( Mat(contours[i]) ); area = contourArea(contours[i],false); if (area < 1){ // cout << "sletter: " << area << endl; contours.erase(contours.begin()+i); minRect.erase(minRect.begin()+i); //area = contourArea(contours[i+1],false); //contours.pop_back(); //cout << i << endl; i--; } else { // minEllipse[i] = fitEllipse( contours[i] ); _mu[i] = moments( Mat(contours[i]), false ); // _mu[i] = moments( Mat(minRect[i]), false ); _mc[i] = Point2f( _mu[i].m10/_mu[i].m00 , _mu[i].m01/_mu[i].m00); _ma[i] = (0.5*atan2(2*_mu[i].mu11,_mu[i].mu20-_mu[i].mu02))*180/M_PI; ROS_INFO("Contour no: %ld Area: %ld Center x: %ld y: %ld Orientation: %ld ", (long int)i,(long int)area,(long int)_mc[i].x, (long int)_mc[i].y, (long int)_ma[i]); ROS_INFO("Contour no: %ld Area: %ld Center x: %ld y: %ld Orientation: %ld ", (long int)i,(long int)area,(long int)minRect[i].center.x, (long int)minRect[i].center.y, (long int)minRect[i].angle); brick.angle = _ma[i]; brick.x = minRect[i].center.x; brick.y = minRect[i].center.y; if (area > 3000 && area < 5000) { brick.type = 2; } else if (area > 7000 && area < 9000){ brick.type = 1; } else if(area > 11000 && area < 13000){ brick.type = 3; } else{ brick.type = 0; } brick_pub.publish(brick); } // cout << "Contour no: " << i << " Area: " << area << " Center x: " << _mc[i].x << " y: " << _mc[i].y << " Orientation: " << _ma[i] << endl; // cout << "Ellipse Orientation: " << minEllipse[i].angle << endl; // cout << oldarea << endl; } Mat drawing = Mat::zeros( imgdest.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); // drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() ); // drawContours( drawing, contours, i, color, CV_FILLED ); // ellipse( drawing, minEllipse[i], color, 2, 8 ); // Point2f rect_points[4]; minRect[i].points( rect_points ); drawCross(_mc[i],Scalar(0,0,255), 5, drawing); Point2f rect_points[4]; minRect[i].points( rect_points ); for( int j = 0; j < 4; j++ ) { line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 ); } char buff[255]; //sprintf(buff, "%d", i+1); string text = std::string(buff); cv::putText(drawing,text,_mc[i],0,0.5,Scalar(0,0,255),1,8,false); // for( int j = 0; j < 4; j++ ) // line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 ); } ROS_INFO("size: %d", contours.size()); /// Show in a window // namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); // imshow( "Contours", drawing ); cv::imshow("image processed", cv_ptr->image); cv::imshow("contours", drawing); //cv::imshow("trackBar1", imgdest); cv::waitKey(3); //Convert the CvImage to a ROS image message and publish it on the "camera/image_processed" topic. pub.publish(cv_ptr->toImageMsg()); }
int main(int, char**) { VideoCapture cap(0); // open the default camera if(!cap.isOpened()){ // check if we succeeded std::cout<<"Terminated since camera init failed"; return -1; } Mat edges; for(;;) { Mat frame; Mat momentMarkedFrame; cap >> frame; // get a new frame from camera Mat filteredFrame = filter_R_pass(frame); momentMarkedFrame = frame; imshow("Filtered", filteredFrame); /* Mat hsv; Mat hue; cvtColor( frame, hsv, CV_BGR2HSV ); /// Use only the Hue value hue.create( hsv.size(), hsv.depth() ); int ch[] = { 0, 0 }; mixChannels( &hsv, 1, &hue, 1, ch, 1 ); hist_backProject(20,hue); */ vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours( filteredFrame, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); Mat drawing = Mat::zeros( filteredFrame.size(), CV_8UC1 ); for( int i = 0; i< contours.size(); i++ ) { vector<Point> contour = contours.at(i); double cArea = contourArea(contour,false); if (cArea>1200){ cout<<"Area "<<i<<" :"<<cArea<<endl; Scalar color = Scalar( rng.uniform(0, 255)); //Find contours's moments Moments m = moments(contour); Point2f center = Point2f(m.m10/m.m00,m.m01/m.m00); circle(momentMarkedFrame,center,5,Scalar(200,200,0),1); imshow("momentMarkedFrame", momentMarkedFrame); drawContours( drawing, contours, i, color, 2, 8, hierarchy, 2, Point() ); } } /// Show in a window namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); //cv::inRange(frame,Scalar(50,50,0),Scalar(60,60,255),redOnlyFrame); //cvtColor(frame, edges, COLOR_BGR2GRAY); //GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5); //Canny(edges, edges, 0, 30, 3); imshow("origin", frame); if(waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return 0; }
bool handReader::bounding(Mat img, Mat skin){ int max_radius = 0; Point2f max_circle; max_radius_index = 0; skinCenter.clear(); threshold(img, img, 0, 255, THRESH_BINARY ); findContours(img, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); vector<vector<Point> > contours_poly( contours.size() ); vector<Rect> boundRect( contours.size() ); vector<Point2f>center( contours.size() ); vector<float>radius( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); boundRect[i] = boundingRect( Mat(contours_poly[i]) ); minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] ); } if(contours.size()==0) return false; /// Draw polygonal contour + bonding rects + circles //Mat drawing = Mat::zeros( img.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ){ Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); //drawContours( img, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() ); //rectangle( img, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 ); if((int)radius[i] > 5){ //circle( img, center[i], (int)radius[i], color, 2, 8, 0 ); for(int x = boundRect[i].tl().x; x < boundRect[i].br().x; x++){ for(int y = boundRect[i].tl().y; y < boundRect[i].br().y; y++){ if(x>=0 && x < img.rows && y >=0 && y < img.cols && skin.data[skin.step[0]*y + skin.step[1]*x + 0] == 255){ img.data[img.step[0]*y + img.step[1]*x + 0] = 255; } } } if(skin.data[skin.step[0]*(int(boundRect[i].tl().y+boundRect[i].br().y)/2) + skin.step[1]*(int(boundRect[i].tl().x+boundRect[i].br().x)/2) + 0] == 255){ skinCenter.push_back(center[i]); if((int)radius[i] > max_radius){ max_radius = (int)radius[i]; max_circle = center[i]; //big_radius_v.push_back(center[i]); } } } } //cout<<skinCenter.size()<<endl; sort (skinCenter.begin(), skinCenter.end(), sortX); //sort (skinCenter.begin(), skinCenter.end(), sortY); if(skinCenter.size()!=0){ //cout <<skinCenter.front().x<<":"<<skinCenter.back().x<<endl; //pathX.push_back(skinCenter); big_radius_v.push_back(max_circle); //max_radius_index.push_back(mri); } //cout<<img.rows<<endl; //cout<<img.cols<<endl; return true; }
namespace CvContour { CvContour::CvContour(const std::string & name) : Base::Component(name) { } CvContour::~CvContour() { } void CvContour::prepareInterface() { // Register handlers with their dependencies. registerHandler("onNewImage", boost::bind(&CvContour::onNewImage, this)); addDependency("onNewImage", &in_img); // Input and output data streams. registerStream("in_img", &in_img); registerStream("out_contours", &out_contours); registerStream("out_img", &out_img); } bool CvContour::onInit() { return true; } bool CvContour::onFinish() { return true; } bool CvContour::onStop() { return true; } bool CvContour::onStart() { return true; } RNG rng(12345); void CvContour::onNewImage() { CLOG(LTRACE) << "CvContour::onNewImage\n"; try { // Input: a binary or edge image. cv::Mat input = in_img.read(); // Find contours. vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours( input, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); /* /// Get the moments vector<Moments> mu(contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mu[i] = moments( contours[i], false ); } /// Get the mass centers: vector<Point2f> mc( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }*/ CLOG(LINFO) << "Found "<< contours.size() << " contours"; // Select only the external contour /* if (contours.size() > 1) contours.erase (contours.begin()+1,contours.end());*/ /// Draw contours Mat drawing = Mat::zeros( input.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() ); // circle( drawing, mc[i], 4, color, -1, 8, 0 ); } // Write contours to the output. out_contours.write(contours); out_img.write(drawing); } catch (...) { CLOG(LERROR) << "CvContour::onNewImage failed\n"; } } } //: namespace CvContour
Mat mClustererCustomKMeans::_cluster(const Mat& descriptors) { cout << "* Creating initial center points *" << endl; // start with random centers, choose from the set of points RNG rng; Mat center_points(Size(descriptors.cols,_getNumClusters()), descriptors.type()); for(int i = 0; i < _getNumClusters(); i++) { int ridx = rng.uniform(0, descriptors.rows); //TODO alternative to use Mat::copyTo center_points.row(i) = descriptors.row(ridx) + Mat::zeros(Size(descriptors.row(ridx).cols, descriptors.row(ridx).rows), descriptors.type()); #ifdef DEBUG cout << " Center Point [" << i << "] " << center_points.row(i) << "; p " << ridx << endl; #endif } Mat lastClusterCenters = center_points; do { lastClusterCenters = center_points; // get nearest points, store points cout << "* Grouping points in clusters *" << endl; vector<vector<Mat> > clusterd_points(_getNumClusters()); for(int i = 0; i < descriptors.rows; i++) { // which cluster the point belongs to // get nearest cluster center to the point double minDist = 1000000; int nearestCluster = 0; for(int ic = 0; ic < _getNumClusters(); ic++) { double dist = Util::getSqDistance(descriptors.row(i), center_points.row(ic)); if (dist < minDist) { minDist = dist; nearestCluster = ic; } } // store point in its corresponding cluster clusterd_points[nearestCluster].push_back(descriptors.row(i)); #ifdef DEBUG cout << " Added point " << descriptors.row(i) << " to cluster [" << nearestCluster << "]; Distance " << minDist << endl; #endif } // recalculate cluster centers cout << "* Recalculate cluster centers *" << endl; for(unsigned int i = 0; i < clusterd_points.size(); i++) { Mat meanM = Util::getMean(clusterd_points[i]); center_points.row(i) = meanM + Mat::zeros(Size(meanM.cols, meanM.rows), meanM.type()); #ifdef DEBUG cout << " Update centre point [" << i << "] " << center_points.row(i) << endl; #endif } cout << "* Checking end condition *" << endl; #ifdef DEBUG cout << "Current center points " << center_points << endl << "Last center points " << lastClusterCenters << endl; #endif // end if the centers stop changing } while(!Util::approximateEq(center_points, lastClusterCenters, 0.1)); return center_points; }
void AmericanOption::Pfadgenerieren(double** X, double** wdiff, int start, double * S) { for (int j = 0; j < D; ++j) X[start][j] = S[j]; // if (PfadModell == GENERISCHE) { // for (int n = start + 1; n < N; ++n) // for (int d = 0; d < D; ++d) // X[n][d] = xi(wdiff[n][d]); // } if (PfadModell == ITO) { for (int n = start + 1; n < N; ++n) for (int d = 0; d < D; ++d) X[n][d] = X[n - 1][d] * exp( (((r - delta) - 0.5 * sigma[d] * sigma[d]) * dt + sigma[d] * wdiff[n][d])); return; } if (PfadModell == LIBOREXP) { double wdiff[D]; for (int n = start + 1; n < N; ++n) { double** zwischen = DoubleFeld(6, D); for (int d = 0; d < D; ++d) zwischen[0][d] = (X[n - 1][d]); double DDT = sqrt(dt / 5.); double RZWISCHEN[D]; double GG[D]; double G[D]; static RNG generator; for (int schritt = 1; schritt < 6; schritt++) { for (int d = 0; d < DrivingFactors; ++d) wdiff[d] = DDT * generator.nextGaussian(); double t = (double) (n - 1) * dt + 0.05 * ((double) schritt - 0.5); zwischen[schritt][0] = log(S[0]); for (int d = 0; d < D; ++d) { RZWISCHEN[d] = (zwischen[schritt - 1][d]); G[d] = 0.2 * g((double) d * dt - t); GG[d] = pow( 0.2 * g( (double) (d + 1) * dt + 0.05 * ((double) schritt - 0.5)), 2); } for (int i = n; i < D; ++i) { double driftsum = 0; for (int j = n; j <= i; ++j) driftsum += dt * RZWISCHEN[j] * G[i] * G[j] * corr[i - 1][j - 1] / (1. + dt * RZWISCHEN[j]); zwischen[schritt][i] = zwischen[schritt - 1][i] * exp( (driftsum - 0.5 * GG[i - n]) * 0.05 + G[i] * prod(chol[i - 1], wdiff, DrivingFactors)); } } for (int d = 0; d < D; ++d) { X[n][d] = zwischen[5][d]; if (d < n) X[n][d] = X[n - 1][d]; } deleteDoubleFeld(zwischen, 6, D); } } // deleteDoubleFeld(wdiff, D); if (X[N - 1][0] < 0) printf("Error0\n"); //if(generator_noch_loeschen)delete generator; }
void IGIIntegrator::Preprocess(const Scene &scene, const Camera *camera, const Renderer *renderer) { if (scene.lights.size() == 0) return; MemoryArena arena; RNG rng; // Compute samples for emitted rays from lights vector<float> lightNum(nLightPaths * nLightSets); vector<float> lightSampPos(2 * nLightPaths * nLightSets, 0.f); vector<float> lightSampComp(nLightPaths * nLightSets, 0.f); vector<float> lightSampDir(2 * nLightPaths * nLightSets, 0.f); LDShuffleScrambled1D(nLightPaths, nLightSets, &lightNum[0], rng); LDShuffleScrambled2D(nLightPaths, nLightSets, &lightSampPos[0], rng); LDShuffleScrambled1D(nLightPaths, nLightSets, &lightSampComp[0], rng); LDShuffleScrambled2D(nLightPaths, nLightSets, &lightSampDir[0], rng); // Precompute information for light sampling densities Distribution1D *lightDistribution = ComputeLightSamplingCDF(scene); for (uint32_t s = 0; s < nLightSets; ++s) { for (uint32_t i = 0; i < nLightPaths; ++i) { // Follow path _i_ from light to create virtual lights int sampOffset = s*nLightPaths + i; // Choose light source to trace virtual light path from float lightPdf; int ln = lightDistribution->SampleDiscrete(lightNum[sampOffset], &lightPdf); Light *light = scene.lights[ln]; // Sample ray leaving light source for virtual light path LightSample ls(lightSampPos[2*sampOffset], lightSampPos[2*sampOffset+1], lightSampComp[sampOffset]); LightInfo2 li = light->Sample_L(scene, ls, lightSampDir[2*sampOffset], lightSampDir[2*sampOffset+1], camera->shutterOpen); RayDifferential ray(li.ray); Spectrum alpha(li.L); if (li.pdf == 0.f || alpha.IsBlack()) continue; alpha /= li.pdf * lightPdf; Intersection isect; auto optIsect = scene.Intersect(ray); while (optIsect && !alpha.IsBlack()) { // Create virtual light and sample new ray for path alpha *= renderer->Transmittance(scene, RayDifferential(ray), NULL, rng, arena); Vector wo = -ray.d; BSDF *bsdf = optIsect->GetBSDF(ray, arena); // Create virtual light at ray intersection point Spectrum contrib = alpha * bsdf->rho(wo, rng) / M_PI; virtualLights[s].push_back(VirtualLight(optIsect->dg.p, optIsect->dg.nn, contrib, optIsect->rayEpsilon)); // Sample new ray direction and update weight for virtual light path Vector wi; float pdf; BSDFSample bsdfSample(rng); Spectrum fr = bsdf->Sample_f(wo, &wi, bsdfSample, &pdf); if (fr.IsBlack() || pdf == 0.f) break; Spectrum contribScale = fr * AbsDot(wi, bsdf->dgShading.nn) / pdf; // Possibly terminate virtual light path with Russian roulette float rrProb = min(1.f, contribScale.y()); if (rng.RandomFloat() > rrProb) break; alpha *= contribScale / rrProb; ray = RayDifferential(optIsect->dg.p, wi, ray, optIsect->rayEpsilon); optIsect = scene.Intersect(ray); } arena.FreeAll(); } } delete lightDistribution; }
/** @function thresh_callback */ void thresh_callback(int, void* ) { Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Detect edges using canny Canny( src_gray, canny_output, thresh, thresh*2, 3 ); /// Find contours findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); // find rotated rectangles and ellipses for each contour vector<RotatedRect> minRect( contours.size() ); vector<RotatedRect> minEllipse( contours.size() ); vector<double> ratio( contours.size() ); vector<double> size( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { minRect[i] = minAreaRect( Mat(contours[i]) ); if( contours[i].size() > contoursizelowbound ) { minEllipse[i] = fitEllipse( Mat(contours[i]) ); cout<< "contour" << endl; Point2f ellipse_points[4]; minEllipse[i].points( ellipse_points ); double majorAxis = sqrt(pow(ellipse_points[0].x - ellipse_points[1].x,2) + pow(ellipse_points[0].y - ellipse_points[1].y,2)); double minorAxis = sqrt(pow(ellipse_points[0].x - ellipse_points[3].x,2) + pow(ellipse_points[0].y - ellipse_points[3].y,2)); ratio[i] = majorAxis/minorAxis; size[i] = majorAxis*minorAxis; //cout<< "ratio = " << ratio[i] << endl; //cout<< "size = " << size[i] << endl; } } /// Draw contours + rotated rects + ellipses Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); Mat drawingContours = Mat::zeros( canny_output.size(), CV_8UC3 ); Mat drawingCells; cvtColor( src, drawingCells, CV_GRAY2BGR ); for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawingContours, contours, i, color, 1, 8, hierarchy, 0, Point() ); //if( ratio[i] > 2 ) if( size[i] < 1000 && size[i] > 100 && ratio[i] < 6) { cout<< "ratio = " << ratio[i] << endl; cout<< "size = " << size[i] << endl; // Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, i, color, 1, 8, hierarchy, 0, Point() ); // ellipse ellipse( drawing, minEllipse[i], color, 1, 8 ); // rotated rectangle //Point2f rect_points[4]; minRect[i].points( rect_points ); //for( int j = 0; j < 4; j++ ) // line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 ); // Draw a line in center of ellipse (major axis over original) // Determine location of points of cell and store in Point2f ellipse_points[4]; minEllipse[i].points( ellipse_points ); Point2f midpt[2]; midpt[0].x = (ellipse_points[0].x + ellipse_points[3].x)/2; midpt[0].y = (ellipse_points[0].y + ellipse_points[3].y)/2; midpt[1].x = (ellipse_points[1].x + ellipse_points[2].x)/2; midpt[1].y = (ellipse_points[1].y + ellipse_points[2].y)/2; // Point2f cellpts; cellpoints[ line( drawingCells, midpt[0], midpt[1], color, 2,8); // Write position of cell in file // write coordinates for each cell's major axis as [x1 y1 x2 y2] cellposn << midpt[0].x <<" "<< midpt[0].y << " " << midpt[1].x <<" " << midpt[1].y <<endl; } } /// Close textfile cellposn.close(); /// Show in a window //namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); //imshow( "Contours", drawing ); // display Canny param and number of contours detected cout <<"Canny = " << thresh << endl; int numContours = contours.size(); cout <<"numContours = " << numContours << endl; /// Show in a window namedWindow( "Filtered Contours", CV_WINDOW_AUTOSIZE ); imshow( "Filtered Contours", drawing ); namedWindow( "All Contours", CV_WINDOW_AUTOSIZE ); imshow( "All Contours", drawingContours ); namedWindow( "Cells", CV_WINDOW_AUTOSIZE ); imshow( "Cells", drawingCells ); imshow( "Source" , canny_output); /// save image; imwrite(IMAGE_PATH+filenamewrite, drawingCells); cout << "image write complete" << endl; }
// Tries to automatically detect the corner points of the go board // This function simply returns without modifying p0, .., p3 if the board couldn't be found void automatic_warp(const Mat& input, Point2f& p0, Point2f& p1, Point2f& p2, Point2f& p3) { // CONVERT TO HSV Mat imgHSV; cvtColor( input, imgHSV, CV_BGR2HSV ); // SPLITTING CHANNELS vector<Mat> v_channel; split(imgHSV, v_channel); //split into three channels // SELECT CHANNEL FOR FURTHER PROCEEDING: SATURATION auto& source_channel = v_channel[1]; // SMOOTHING IMAGE medianBlur(source_channel, source_channel, 3); // BINARY THRESH THE IMAGE const auto threshold = cv::threshold(source_channel, source_channel, 0, 255, THRESH_BINARY | THRESH_OTSU); // FINDING CONTOURS Mat clone = source_channel.clone(); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(clone, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0)); // STOP IF THERE AREN'T ANY CONTOURS if (contours.size() == 0) return; // APPROX. CONTOURS TO RECTANGLES const auto factor = .065f; // found through testing! for (auto& contour : contours) { // approximating each contour to get a rectangle with 4 points! approxPolyDP(Mat(contour), contour, arcLength(Mat(contour), true)*factor, true); } // CALCULATING BBOXES vector<Rect> bboxes; for (const auto& contour : contours) bboxes.push_back(boundingRect(contour)); // CALCULATING MEAN BBOX AREA int bbox_area_sum = accumulate(begin(bboxes), end(bboxes), 0, [](int base, const Rect& r) { return base + r.area(); }); int mean_area = bbox_area_sum/contours.size(); // DELETING IMPROPER CONTOURS/BBOXES // that are smaller than the mean area // or almost as big as the whole image // or don't have exactly 4 corner points after approximation ( == rectangle) assert(bboxes.size() == contours.size()); // for discarding contours that contain the complete image const float edge_factor = .99f; const float max_width = input.cols * edge_factor; const float max_height = input.rows * edge_factor; // DEBUG: DRAWING ALL LEFTOVER CONTOURS Mat drawing = input.clone(); for (size_t i = 0; i < contours.size(); ++i) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)); drawContours(drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point()); } // DEBUG: DRAWING BBOXES FOR ALL CONTOURS for(auto& rect : bboxes) { rectangle(drawing, rect.tl(), rect.br(), Scalar(255, 255, 255), 2, 8); } auto cont_it = begin(contours); auto bbox_it = begin(bboxes); while (cont_it != end(contours) && bbox_it != end(bboxes)) { auto& contour = *cont_it; auto& bbox = *bbox_it; const auto ar = bbox.area(); // delete bboxes and its corresponding contour if the bbox is almost as large as the window if (bbox.width >= max_width && bbox.height >= max_height) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } // or if the bbox area is smaller than the mean area else if (bbox.area() <= mean_area) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } else if (contour.size() != 4) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } else { ++cont_it; ++bbox_it; } } // STOP IF WE DON'T HAVE ANY CONTOURS LEFT -> NO BOARD FOUND if (contours.size() == 0) return; // SELECTING SUITABLE CONTOUR // sort contours and bboxes by area // that means we're selecting biggest contour for further processing if (contours.size() > 1) { sort(begin(contours), end(contours), [](const vector<Point>& cont1, const vector<Point>& cont2) { return contourArea(cont1) > contourArea(cont2); } ); sort(begin(bboxes), end(bboxes), [](const Rect& r1, const Rect& r2) { return r1.area() > r2.area(); } ); } auto board_contour = contours.front(); auto board_bbox = bboxes.front(); // GETTING CORNER POINTS OF CONTOUR // stop if the contour has left only 4 points after approximating if (board_contour.size() != 4) return; // Rectangle Order for warping: // 0--------1 // | | // | | // 2--------3 auto center = Point(board_bbox.x + board_bbox.width/2, board_bbox.y + board_bbox.height/2); // splitting points in upper and lower half vector<Point> uppers, lowers; for (auto& point : board_contour) { if (point.y < center.y) uppers.emplace_back(point); else lowers.emplace_back(point); } // stop if we couldn't classify two uppers and lowers if (uppers.size() != 2 || lowers.size() != 2) return; // deciding which point is left/right // upper side p0 = uppers[0]; p1 = uppers[1]; if (p0.x > p1.x) swap(p0, p1); // lower side p2 = lowers[0]; p3 = lowers[1]; if (p2.x < p3.x) swap(p2, p3); }
int main() { cout << "input block : "; char name; cin >> name; VideoCapture cap(0); if (!cap.isOpened())return 0; vector<Mat> RoiSet; Mat sub, draw_sub; vector<vector<Point> > contours; vector<Vec4i> hierarchy; Rect rect; Mat diff; uchar *myData; dis_feature dis_calcul; CircleFeature cir_calcul; cir_calcul.makeCircle(); vector<int> vcir; Mat whiteBalance; int avr = 100; //////////////////////////////// /*int hlow = 0, hhigh = 255; int slow = 0, shigh = 255; int vlow = 0, vhigh = 255; int canlow = 0, canhigh = 255;*/ //////////////////////////////// while (1) { while (1)//차영상 이용해서 break { Mat avrimg; cap >> avrimg; for (int i = 0; i < avr; i++) { cap >> img; //if (img.empty())goto out; resize(avrimg, avrimg, Size(), ratio, ratio);//이미지 리사이징 getaccAvr(img, avrimg);//중첩영상 만들기 } if (!flag) { whiteBalance = avrimg; flag = !flag; avr = 10; }//처음 한번만 밸런스 매트릭스를 만든다 int height = 0, width = 0; int _stride = 0; float cnt1 = 0, wide = 0; Mat imgry, avrgry; imshow("balance_mat", whiteBalance); cvtColor(img, imgry, CV_BGR2GRAY); cvtColor(avrimg, avrgry, CV_BGR2GRAY); absdiff(imgry, avrgry, diff); threshold(diff, diff, 20, 255, THRESH_BINARY); //imshow("diff", diff); height = diff.rows; width = diff.cols; wide = height*width; _stride = diff.step; myData = diff.data; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { uchar val = myData[i * _stride + j]; if (val)cnt1++; } } //cout << cnt1 << " " << wide << " " << cnt1 / wide << endl; if (cnt1 / wide < 0.01) { avrimg.copyTo(img); break; } if (waitKey(1) == 27)goto out; } Mat temp; cv::scaleAdd(whiteBalance, -0.1, img, img); absdiff(whiteBalance, img, img); imshow("balance img", img); ////////////////////////trackbar////////////////////// /*namedWindow("track", 1); createTrackbar("Hlow_value", "track", &canlow, 255); createTrackbar("Hhigh_value", "track", &canhigh, 255); createTrackbar("Slow_value", "track", &slow, 255); createTrackbar("Shigh_value", "track", &shigh, 255); createTrackbar("Vlow_value", "track", &vlow, 255); createTrackbar("Vhigh_value", "track", &vhigh, 255);*/ ////////////////////////////////////////////////////// img.copyTo(sub); GaussianBlur(img, img, Size(3, 3), 0.8); //cvtColor(img, img, COLOR_BGR2HSV); //inRange(img, Scalar(hlow, slow, vlow), Scalar(hhigh, shigh, vhigh), img); //cvtColor(img, img, COLOR_BGR2GRAY); Canny(img, temp, 30, 200); //threshold(~img, img, 100, 255, THRESH_BINARY); findContours(temp, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); draw_sub = Mat::zeros(temp.size(), CV_8UC3); vector<Point> approxShape; for (size_t i = 0; i < contours.size(); i++) { approxPolyDP(contours[i], approxShape, arcLength(Mat(contours[i]), true)*0.04, true); drawContours(draw_sub, contours, i, Scalar(255, 255, 255), CV_FILLED); } imshow("draw_sub", draw_sub); Canny(draw_sub, temp, 0, 255); imshow("temp2", temp); findContours(temp, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); /*Mat temp_; Mat element = getStructuringElement(cv::MORPH_GRADIENT, cv::Size(3, 3), cv::Point(3, 3)); draw_sub.copyTo(temp_); erode(temp_, temp_, element); absdiff(draw_sub, temp_, draw_sub); findContours(draw_sub, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); */ vector<RotatedRect> minRect(contours.size()); vector<RotatedRect> minEllipse(contours.size()); setMouseCallback("src", CallBackFunc, NULL); RoiSet.clear(); for (int i = 0; i < contours.size(); i++) { minRect[i] = minAreaRect(Mat(contours[i])); if (contours[i].size()>5) { minEllipse[i] = fitEllipse(Mat(contours[i])); } } int j = 0; vector<float> width_length; vector<location> loc; vector<Point2f> cen_for_loc; system("cls"); for (int i = 0; i < contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); width_length.clear(); float div = 0; Point2f rect_point[4]; Point2f center; minRect[i].points(rect_point); Mat M, rotated; location tmp; float angle = minRect[i].angle; Size Rrect_size = minRect[i].size; if (minRect[i].angle < -45.) { angle += 90.0; swap(Rrect_size.width, Rrect_size.height); } M = getRotationMatrix2D(minRect[i].center, angle, 1.0); warpAffine(draw_sub, rotated, M, draw_sub.size(), INTER_CUBIC); getRectSubPix(rotated, Rrect_size, minRect[i].center, rotated); char num[10]; sprintf(num, "#%d img", j); for (int j = 0; j < 4; j++) { width_length.push_back(dis_calcul.point_dist(rect_point[j], rect_point[(j + 1) % 4])); } div = width_length[0] < width_length[1] ? width_length[0] / width_length[1] : width_length[1] / width_length[0]; if ((rotated.cols * rotated.rows>2000))//&& (div>0.5))// && (div < 0.9)) { for (int j = 0; j < 4; j++) { line(sub, rect_point[j], rect_point[(j + 1) % 4], Scalar(255, 0, 0)); center.x += rect_point[j].x; center.y += rect_point[j].y; } center.x /= 4; cvtColor(rotated, rotated, COLOR_BGR2HSV); inRange(rotated, Scalar(0, 0, 0), Scalar(255, 255, 125), rotated); //imshow("rotated", rotated); //rotated = ~rotated; //cout << num << " : " << dis_calcul.dev_from_mat(rotated) << endl; cir_calcul.CircleByMat(rotated); cir_calcul.rtFullCirnum(rotated, vcir); vcir.clear(); tmp.set_pt(center); cen_for_loc.push_back(center); /////// //class에 값 집어넣는 과정 char decided = decision_making(name,rotated); tmp.set_data(decided); /////// loc.push_back(tmp); imshow(num, rotated); cout << num << "::" << decided << endl; j++; } } for (int k = 0; k < loc.size(); k++) { loc[k].set_rnk(get_rnk_pt(cen_for_loc)); } print_loc(sub, get_rnk_pt(cen_for_loc)); //imshow("img", img); imshow("src", sub); if (waitKey(5) == 27)break; } out: destroyAllWindows(); return 0; }
namespace Go_Scanner { const char* thresh_window = "Thresh"; const char* morph_window = "Morph"; bool asked_for_board_contour = false; using namespace cv; using namespace std; //point coordinates int boardCornerX[]={80, 443, 460, 157}; int boardCornerY[]={80, 87, 430, 325}; Mat img0, selectedImg, temp; string windowName = "Manual Selection Window"; int board_selection_cancel_key = 27; // split a string at each char that is contained in delimiters and return the tokens vector<string> split(const string& str, const string& delimiters) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); vector<string> tokens; while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } return tokens; } // renders a text in img with text at position // automatically handels newlines void putText(Mat img, string text, Point position) { // text appearence int fontFace = 1; double fontScale = 1.2; int thickness = 1; int baseline = 0; int offset_x = 1, offset_y = 3; // text size of one line Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; auto total_height = textSize.height + baseline + 1; auto lines = split(text, "\n"); // recurse if we got more than one line // and put each line directly under the preceding if (lines.size() > 1) { int i = 0; for (const auto& line : lines) { putText(img, line, position + Point(0, i*total_height)); ++i; } return; } // buffer for the transparent box under the text (achieved through blending the images) Mat box_buf = img.clone(); // draw the solid box rectangle(box_buf, position + Point(0, baseline), position + Point(textSize.width, -textSize.height), Scalar(0, 0, 0), CV_FILLED); // blend the box to make it transparent auto alpha = .3f; addWeighted(box_buf, alpha, img, 1.0 - alpha, 0.0, img); // draw the baseline line(img, position + Point(0, thickness + offset_y), position + Point(textSize.width, thickness + offset_y), Scalar(0, 0, 255)); // draw the actual text putText(img, text, position + Point(offset_x, offset_y), // position fontFace, // font face fontScale, // font scale Scalar(64, 64, 255), // color thickness, // thickness CV_AA); // line type } /** * @brief Calls the manual board detection and shows the result in a new window. */ void ask_for_board_contour() { namedWindow(windowName, CV_WINDOW_AUTOSIZE); setMouseCallback(windowName, mouseHandler, NULL); putText(img0, "Mark the Go board with the blue rectangle\n" "Press ESC to cancel or any other key to accept.", cvPoint(10, 20)); showImage(); auto key = waitKey(0); destroyWindow(windowName); // only accept board selection if the ESCAPE key was NOT pressed! if (key != board_selection_cancel_key) asked_for_board_contour = true; } /** * @brief Calls the automatic board detection and shows the result in a new window. * Prints an error to the console if the automatic detection couldn't find anything. */ void do_auto_board_detection() { Point2f p0, p1, p2, p3; automatic_warp(img0, p0, p1, p2, p3); // automatic_warp failed and board wasn't found // if one of the points wasn't set if (p0 == Point2f()) { cout << "!!ERROR >> Failed to automatically detect the go board!" << endl; ask_for_board_contour(); return; } // HACK: adjust the coordinates a bit to snap them closer to the board grid const auto gap = .5f; p0 += Point2f(gap, gap); p1 += Point2f(-gap, gap); p2 += Point2f(-gap, -gap); p3 += Point2f(gap, -gap); // create data suitable for showImage() int board_corners_X[] = { (int)p0.x, (int)p1.x, (int)p2.x, (int)p3.x }; int board_corners_Y[] = { (int)p0.y, (int)p1.y, (int)p2.y, (int)p3.y }; namedWindow(windowName, CV_WINDOW_AUTOSIZE); putText(img0, "Result of automatically detecting the Go board.\n" "Press ESC to cancel or any other key to accept.", cvPoint(10, 20)); showImage(board_corners_X, board_corners_Y); auto key = waitKey(0); destroyWindow(windowName); // only accept board selection if the ESCAPE key was NOT pressed! if (key != board_selection_cancel_key) { asked_for_board_contour = true; // actually commmit the selection to the internal used variables boardCornerX[0] = cvRound(p0.x); boardCornerX[1] = cvRound(p1.x); boardCornerX[2] = cvRound(p2.x); boardCornerX[3] = cvRound(p3.x); boardCornerY[0] = cvRound(p0.y); boardCornerY[1] = cvRound(p1.y); boardCornerY[2] = cvRound(p2.y); boardCornerY[3] = cvRound(p3.y); } } Mat warpImage(Mat img, Point2f p0, Point2f p1, Point2f p2, Point2f p3) { /* Rectangle Order: 0-------1 | | | | 2-------3 */ Point2f selCorners[4]; selCorners[0] = p0; selCorners[1] = p1; selCorners[2] = p2; selCorners[3] = p3; Point2f dstCorners[4]; dstCorners[0] = Point2f(0.0, 0.0); dstCorners[1] = Point2f((float)img.cols, 0.0); dstCorners[2] = Point2f(0.0, (float)img.rows); dstCorners[3] = Point2f((float)img.cols, (float)img.rows); Mat transformationMatrix; transformationMatrix = getPerspectiveTransform(selCorners, dstCorners); Mat warpedImg; warpPerspective(img, warpedImg, transformationMatrix, warpedImg.size(), 1, 0 ,0); return warpedImg; } RNG rng(12345); // Tries to automatically detect the corner points of the go board // This function simply returns without modifying p0, .., p3 if the board couldn't be found void automatic_warp(const Mat& input, Point2f& p0, Point2f& p1, Point2f& p2, Point2f& p3) { // CONVERT TO HSV Mat imgHSV; cvtColor( input, imgHSV, CV_BGR2HSV ); // SPLITTING CHANNELS vector<Mat> v_channel; split(imgHSV, v_channel); //split into three channels // SELECT CHANNEL FOR FURTHER PROCEEDING: SATURATION auto& source_channel = v_channel[1]; // SMOOTHING IMAGE medianBlur(source_channel, source_channel, 3); // BINARY THRESH THE IMAGE const auto threshold = cv::threshold(source_channel, source_channel, 0, 255, THRESH_BINARY | THRESH_OTSU); // FINDING CONTOURS Mat clone = source_channel.clone(); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(clone, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0)); // STOP IF THERE AREN'T ANY CONTOURS if (contours.size() == 0) return; // APPROX. CONTOURS TO RECTANGLES const auto factor = .065f; // found through testing! for (auto& contour : contours) { // approximating each contour to get a rectangle with 4 points! approxPolyDP(Mat(contour), contour, arcLength(Mat(contour), true)*factor, true); } // CALCULATING BBOXES vector<Rect> bboxes; for (const auto& contour : contours) bboxes.push_back(boundingRect(contour)); // CALCULATING MEAN BBOX AREA int bbox_area_sum = accumulate(begin(bboxes), end(bboxes), 0, [](int base, const Rect& r) { return base + r.area(); }); int mean_area = bbox_area_sum/contours.size(); // DELETING IMPROPER CONTOURS/BBOXES // that are smaller than the mean area // or almost as big as the whole image // or don't have exactly 4 corner points after approximation ( == rectangle) assert(bboxes.size() == contours.size()); // for discarding contours that contain the complete image const float edge_factor = .99f; const float max_width = input.cols * edge_factor; const float max_height = input.rows * edge_factor; // DEBUG: DRAWING ALL LEFTOVER CONTOURS Mat drawing = input.clone(); for (size_t i = 0; i < contours.size(); ++i) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)); drawContours(drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point()); } // DEBUG: DRAWING BBOXES FOR ALL CONTOURS for(auto& rect : bboxes) { rectangle(drawing, rect.tl(), rect.br(), Scalar(255, 255, 255), 2, 8); } auto cont_it = begin(contours); auto bbox_it = begin(bboxes); while (cont_it != end(contours) && bbox_it != end(bboxes)) { auto& contour = *cont_it; auto& bbox = *bbox_it; const auto ar = bbox.area(); // delete bboxes and its corresponding contour if the bbox is almost as large as the window if (bbox.width >= max_width && bbox.height >= max_height) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } // or if the bbox area is smaller than the mean area else if (bbox.area() <= mean_area) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } else if (contour.size() != 4) { cont_it = contours.erase(cont_it); bbox_it = bboxes.erase(bbox_it); } else { ++cont_it; ++bbox_it; } } // STOP IF WE DON'T HAVE ANY CONTOURS LEFT -> NO BOARD FOUND if (contours.size() == 0) return; // SELECTING SUITABLE CONTOUR // sort contours and bboxes by area // that means we're selecting biggest contour for further processing if (contours.size() > 1) { sort(begin(contours), end(contours), [](const vector<Point>& cont1, const vector<Point>& cont2) { return contourArea(cont1) > contourArea(cont2); } ); sort(begin(bboxes), end(bboxes), [](const Rect& r1, const Rect& r2) { return r1.area() > r2.area(); } ); } auto board_contour = contours.front(); auto board_bbox = bboxes.front(); // GETTING CORNER POINTS OF CONTOUR // stop if the contour has left only 4 points after approximating if (board_contour.size() != 4) return; // Rectangle Order for warping: // 0--------1 // | | // | | // 2--------3 auto center = Point(board_bbox.x + board_bbox.width/2, board_bbox.y + board_bbox.height/2); // splitting points in upper and lower half vector<Point> uppers, lowers; for (auto& point : board_contour) { if (point.y < center.y) uppers.emplace_back(point); else lowers.emplace_back(point); } // stop if we couldn't classify two uppers and lowers if (uppers.size() != 2 || lowers.size() != 2) return; // deciding which point is left/right // upper side p0 = uppers[0]; p1 = uppers[1]; if (p0.x > p1.x) swap(p0, p1); // lower side p2 = lowers[0]; p3 = lowers[1]; if (p2.x < p3.x) swap(p2, p3); } //Manual detection /* Rectangle Order: 0-------1 | | | | 3-------2 */ int point=-1; //currently selected point int nop=4; //number of points void mouseHandler(int event, int x, int y, int flags, void *param) { switch(event) { case CV_EVENT_LBUTTONDOWN: selectedImg = holdImg(x, y); break; case CV_EVENT_LBUTTONUP: if((selectedImg.empty()!= true)&& point!=-1) { releaseImg(selectedImg,x,y); selectedImg=Mat(); } break; //Draws the lines while navigating with the mouse case CV_EVENT_MOUSEMOVE: /* draw a rectangle*/ if(point!=-1) { if(selectedImg.empty()!= true) { temp = selectedImg.clone(); rectangle(temp, Point(x - 10, y - 10), Point(x + 10, y + 10), //BGR not RGB!! Scalar(0, 255, 0, 0), 2, 8, 0); //adjust the lines for(int i=0;i<nop;i++) { if(i!=point) { line(temp, Point(x, y), Point(boardCornerX[i] , boardCornerY[i] ), Scalar(0, 255, 0 ,0), 1,8,0); } } imshow(windowName, temp); } break; } temp = Mat(); } } //draws the lines and points while holding left mouse button down Mat holdImg(int x, int y) { Mat img = img0; int radius = 4; //find what point is selected for(int i=0;i<nop;i++){ if((x>=(boardCornerX[i]-radius)) && (x<=(boardCornerX[i]+radius ))&& (y<=(boardCornerY[i]+radius ))&& (y<=(boardCornerY[i]+radius ))){ point=i; break; } } //draw points for(int j=0;j<nop;j++) { //if this is not the selected point if(j!=point) { img = img.clone(); rectangle(img, Point(boardCornerX[j] - 1, boardCornerY[j] - 1), Point(boardCornerX[j] + 1, boardCornerY[j] + 1), Scalar(255, 0, 0, 0), 2, 8, 0); } } //draw lines for(int i=0;i<nop;i++) { if(i!=point) { for(int k=i+1;k<nop;k++) { if(k!=point) { img = img.clone(); line(img, Point(boardCornerX[i] , boardCornerY[i] ), Point(boardCornerX[k] , boardCornerY[k] ), Scalar(255, 0, 0, 0), 1,8,0); } } } } return img; } //set new coordinates and redraw the scene if the left mouse button is released void releaseImg(Mat a, int x, int y) { boardCornerX[point]=x; boardCornerY[point]=y; showImage(); } /** * @brief Shows the points given through the two passed parameters on a clone of the img0 in a new window. * Both pointers have to point to memory containing 4 variables */ void showImage(int* board_corner_X, int* board_corner_Y) { Mat img1 = img0.clone(); //draw the points for(int j=0;j<nop;j++) { rectangle(img1, Point(board_corner_X[j] - 1, board_corner_Y[j] - 1), Point(board_corner_X[j] + 1, board_corner_Y[j] + 1), Scalar(255, 0, 0, 0), 2, 8, 0); //draw the lines for(int k=j+1;k<nop;k++) { line(img1, Point(board_corner_X[j] , board_corner_Y[j] ), Point(board_corner_X[k] , board_corner_Y[k] ), Scalar(255, 0, 0, 0), 1,8,0); } } imshow(windowName, img1); } /** * @brief Shows the selected points (through manual or automatic board detection) on a clone of the img0 in a new window. */ void showImage() { showImage(boardCornerX, boardCornerY); } bool getWarpedImg(Mat& warpedImg) { img0 = warpedImg.clone(); // only process the image if the user selected the board with "ask_for_board_contour" or "do_auto_board_detection" once. // this is triggered through the GUI (and the Scanners selectBoardManually() and selectBoardAutomatically() methods) if (!asked_for_board_contour) { return false; } warpedImg = warpImage(img0, Point2i(boardCornerX[0], boardCornerY[0]), Point2i(boardCornerX[1], boardCornerY[1]), Point2i(boardCornerX[3], boardCornerY[3]), Point2i(boardCornerX[2], boardCornerY[2])); return true; } }
int _tmain(int argc, _TCHAR* argv[]) { VideoCapture cap(0); // open the video camera no. 0 if (!cap.isOpened()) // if not success, exit program { cout << "Cannot open the video cam" << endl; return -1; } double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout << "Frame size : " << dWidth << " x " << dHeight << endl; // namedWindow("BlackWhite", CV_WINDOW_AUTOSIZE); namedWindow("Gray", CV_WINDOW_AUTOSIZE); namedWindow("Blur", CV_WINDOW_AUTOSIZE); namedWindow("BlackWhite", CV_WINDOW_AUTOSIZE); namedWindow("Canny", CV_WINDOW_AUTOSIZE); namedWindow("FindContours", CV_WINDOW_AUTOSIZE); namedWindow("Result", CV_WINDOW_AUTOSIZE); while (1) { Mat frame; bool bSuccess = cap.read(frame); // read a new frame from video if (!bSuccess) //if not success, break loop { cout << "Cannot read a frame from video stream" << endl; break; } // process Mat frameGray; Mat frameBlur; Mat frameBlackWhite; Mat frameCanny; Mat frameGrayResize; Mat frameBlurResize; Mat frameBlackWhiteResize; Mat frameCannyResize; cvtColor(frame, frameGray, CV_BGR2GRAY); blur(frameGray, frameBlur, Size(9, 9)); threshold(frameBlur, frameBlackWhite, 80, 255, THRESH_BINARY); // calcul de l'air (calculer le nombre de pixels blancs) // imshow("BlackWhite", frameGray); vector<vector<Point> > contours; vector<Vec4i> hierarchy; Canny(frameBlackWhite, frameCanny, thresh, thresh * 2, 3); findContours(frameCanny, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); int index = 0; vector<Point> bestContour; int perimeter = getPerimeter(contours, index, bestContour); int xmin = INT_MAX, xmax = -INT_MAX, ymin = INT_MAX, ymax = -INT_MAX; getHandArea(bestContour, xmin, xmax, ymin, ymax); int area = getArea(xmin, xmax, ymin, ymax, frameBlackWhite); // rapport aire / périmètre double rap1 = (double)area / (double)((xmax - xmin) * (ymax - ymin) - area); double rap2 = (double)area / (double)perimeter; // std::cout << perimeter << std::endl; // cout << "contours size: " << contours.size() << endl; Mat frameFindContours = Mat::zeros(frameCanny.size(), CV_8UC3); Mat drawing = Mat::zeros(frameCanny.size(), CV_8UC3); Mat frameFindContoursResize; Mat drawingResize; for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)); drawContours(frameFindContours, contours, i, color, 2, 8, hierarchy, 0, Point()); } // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); Scalar color = Scalar(200, 200, 250); drawContours(drawing, contours, index, color, 2, 8, hierarchy, 0, Point()); double rapF = rap1 * rap2; displayText("Perimeter = " + std::to_string(perimeter), 10, 20, drawing); displayText("Area = " + std::to_string(area), 10, 50, drawing); displayText("Rapport pixel blanc noir = " + std::to_string(rap1), 10, 80, drawing); displayText("Rapport perimeter area = " + std::to_string(rap2), 10, 110, drawing); displayText("Rapport final = " + std::to_string(rapF), 10, 140, drawing); displayText("Result = " + getResult(rapF, rap1), 10, 170, drawing); rectangle(drawing, cvPoint(xmin, ymin), cvPoint(xmax, ymax), cvScalar(255, 0, 0)); // resize // old 640x480 // new 320x240 or 160x120 Size newSize = Size(500, 340); resize(frameGray, frameGrayResize, newSize); resize(frameBlur, frameBlurResize, newSize); resize(frameBlackWhite, frameBlackWhiteResize, newSize); resize(frameCanny, frameCannyResize, newSize); resize(frameFindContours, frameFindContoursResize, newSize); resize(drawing, drawingResize, newSize); imshow("Gray", frameGrayResize); imshow("Blur", frameBlurResize); imshow("BlackWhite", frameBlackWhiteResize); imshow("Canny", frameCannyResize); imshow("FindContours", frameFindContoursResize); imshow("Result", drawingResize); int offsetX = newSize.width + 30; int offsetY = newSize.height + 50; moveWindow("Gray", 0, 0); moveWindow("Blur", offsetX, 0); moveWindow("BlackWhite", 2 * offsetX, 0); moveWindow("Canny", 0, offsetY); moveWindow("FindContours", offsetX, offsetY); moveWindow("Result", 2 * offsetX, offsetY); if (waitKey(30) == 27) { cout << "esc key is pressed by user" << endl; break; } } return 0; }
void StateSet::init_to_gaussian_noise(RNG& rng) { for (size_t n=0; n<N; n++) for (size_t y=0; y<datalayout.sizey; y++) for (size_t x=0; x<datalayout.sizex; x++) data(n,x,y) = comp(rng.gaussian_rand(), rng.gaussian_rand()); }
void VolumePatIntegrator::EyeRandomWalk(const Scene *scene, const Ray &eyeRay, VolumeVertexList& vertexList, RNG &rng) const { // Do a random walk for the eye ray in the volume Spectrum cummulative(1.f); // Find the intersection between the eye ray and the volume VolumeRegion *vr = scene->volumeRegion; float t0, t1; if (!vr || !vr->IntersectP(eyeRay, &t0, &t1) || (t1-t0) == 0.f || t0 < 0.f) { return; } // Find the intersection point between the sampled light ray and the volume RayDifferential ray(eyeRay); Point p = ray(t0), pPrev; uint64_t bounces = 0; while(vr->WorldBound().Inside(p)) { Vector wi = -ray.d; const Spectrum sigma_a = vr->Sigma_a(p, wi, eyeRay.time); const Spectrum sigma_s = vr->Sigma_s(p, wi, eyeRay.time); const Spectrum STER = vr->STER(p, wi, eyeRay.time); // Construct and add the _eyeVertex_ to the _vertexList_ VolumeVertex eyeVertex(p, wi, sigma_a, sigma_s, cummulative, 1.0); vertexList.push_back(eyeVertex); // Sample the direction of the next event float directionPdf = 1.f; Vector wo; if(STER.y() > rng.RandomFloat()) { // Change the ray direction due to a scattering event at _p_ if(!vr->SampleDirection(p, wi, wo, &directionPdf, rng)) { break; // Direction error } // Account for the losses due to the scattering event at _p_ cummulative *= sigma_s * vr->p(p, wi, wo, ray.time); } else { // Account only for the trnsmittance between the previous and the // next events becuse there is no direction change. wo = ray.d; } // Sample the distance of the next event ray = RayDifferential(p, wo, 0, INFINITY); float tDist; float distancePdf = 1.f; Point Psample; if(!vr->SampleDistance(ray, &tDist, Psample, &distancePdf, rng)) { break; // The sampled point is outside the volume } // Account for the sampling Pdfs from sampling a direction and/or distance const float pdf = distancePdf * directionPdf; cummulative *= 1 / pdf; // Update the events and account for the transmittance between the events pPrev = p; p = Psample; const Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, ray.time, ray.depth); const Spectrum stepTau = vr->tau(tauRay, .5f * stepSize, rng.RandomFloat()); const Spectrum TrPP = Exp(-stepTau); cummulative *= TrPP; // Possibly terminate ray marching if _cummulative_ is small if (cummulative.y() < 1e-3) { const float continueProb = .5f; if (rng.RandomFloat() > continueProb) { cummulative = 0.f; break; } cummulative /= continueProb; } // Terminate if bounces are more than requested bounces++; if (bounces > maxDepth) { break; } } }
TEST_P(Eltwise, Accuracy) { Vec3i inSize = get<0>(GetParam()); std::string op = get<1>(GetParam()); int numConv = get<2>(GetParam()); bool weighted = get<3>(GetParam()); Net net; std::vector<int> convLayerIds(numConv); for (int i = 0; i < numConv; ++i) { Mat weights({inSize[0], inSize[0], 1, 1}, CV_32F); randu(weights, -1.0f, 1.0f); LayerParams convParam; convParam.set("kernel_w", 1); convParam.set("kernel_h", 1); convParam.set("num_output", inSize[0]); convParam.set("bias_term", false); convParam.type = "Convolution"; std::ostringstream ss; ss << "convLayer" << i; convParam.name = ss.str(); convParam.blobs.push_back(weights); convLayerIds[i] = net.addLayer(convParam.name, convParam.type, convParam); net.connect(0, 0, convLayerIds[i], 0); } LayerParams eltwiseParam; eltwiseParam.set("operation", op); if (op == "sum" && weighted) { RNG rng = cv::theRNG(); std::vector<float> coeff(1 + numConv); for (int i = 0; i < coeff.size(); ++i) { coeff[i] = rng.uniform(-2.0f, 2.0f); } eltwiseParam.set("coeff", DictValue::arrayReal<float*>(&coeff[0], coeff.size())); } eltwiseParam.type = "Eltwise"; eltwiseParam.name = "testLayer"; int eltwiseId = net.addLayer(eltwiseParam.name, eltwiseParam.type, eltwiseParam); net.connect(0, 0, eltwiseId, 0); for (int i = 0; i < numConv; ++i) { net.connect(convLayerIds[i], 0, eltwiseId, i + 1); } Mat input({1, inSize[0], inSize[1], inSize[2]}, CV_32F); randu(input, -1.0f, 1.0f); net.setInput(input); Mat outputDefault = net.forward(eltwiseParam.name).clone(); net.setPreferableBackend(DNN_BACKEND_HALIDE); Mat outputHalide = net.forward(eltwiseParam.name).clone(); normAssert(outputDefault, outputHalide); }
void ompl::geometric::pSBL::threadSolve(unsigned int tid, const base::PlannerTerminationCondition &ptc, SolutionInfo *sol) { RNG rng; std::vector<Motion*> solution; base::State *xstate = si_->allocState(); bool startTree = rng.uniformBool(); while (!sol->found && ptc == false) { bool retry = true; while (retry && !sol->found && ptc == false) { removeList_.lock.lock(); if (!removeList_.motions.empty()) { if (loopLock_.try_lock()) { retry = false; std::map<Motion*, bool> seen; for (unsigned int i = 0 ; i < removeList_.motions.size() ; ++i) if (seen.find(removeList_.motions[i].motion) == seen.end()) removeMotion(*removeList_.motions[i].tree, removeList_.motions[i].motion, seen); removeList_.motions.clear(); loopLock_.unlock(); } } else retry = false; removeList_.lock.unlock(); } if (sol->found || ptc) break; loopLockCounter_.lock(); if (loopCounter_ == 0) loopLock_.lock(); loopCounter_++; loopLockCounter_.unlock(); TreeData &tree = startTree ? tStart_ : tGoal_; startTree = !startTree; TreeData &otherTree = startTree ? tStart_ : tGoal_; Motion *existing = selectMotion(rng, tree); if (!samplerArray_[tid]->sampleNear(xstate, existing->state, maxDistance_)) continue; /* create a motion */ Motion *motion = new Motion(si_); si_->copyState(motion->state, xstate); motion->parent = existing; motion->root = existing->root; existing->lock.lock(); existing->children.push_back(motion); existing->lock.unlock(); addMotion(tree, motion); if (checkSolution(rng, !startTree, tree, otherTree, motion, solution)) { sol->lock.lock(); if (!sol->found) { sol->found = true; PathGeometric *path = new PathGeometric(si_); for (unsigned int i = 0 ; i < solution.size() ; ++i) path->append(solution[i]->state); pdef_->addSolutionPath(base::PathPtr(path), false, 0.0, getName()); } sol->lock.unlock(); } loopLockCounter_.lock(); loopCounter_--; if (loopCounter_ == 0) loopLock_.unlock(); loopLockCounter_.unlock(); } si_->freeState(xstate); }
void DrawRectangle(Mat& img, Rect box) { //Draw a rectangle with random color rectangle(img, box.tl(), box.br(), Scalar(g_rng.uniform(0, 255), g_rng.uniform(0,255),g_rng.uniform(0,255))); }
static Mat DrawMyImage(int thickness,int nbShape) { Mat img=Mat::zeros(500,256*thickness+100,CV_8UC1); int offsetx = 50, offsety = 25; int lineLenght = 50; for (int i=0;i<256;i++) line(img,Point(thickness*i+ offsetx, offsety),Point(thickness*i+ offsetx, offsety+ lineLenght),Scalar(i), thickness); RNG r; Point center; int radius; int width,height; int angle; Rect rc; for (int i=1;i<=nbShape;i++) { int typeShape = r.uniform(MyCIRCLE, MyELLIPSE+1); switch (typeShape) { case MyCIRCLE: center = Point(r.uniform(offsetx,img.cols- offsetx), r.uniform(offsety + lineLenght, img.rows - offsety)); radius = r.uniform(1, min(offsetx, offsety)); circle(img,center,radius,Scalar(i),-1); break; case MyRECTANGLE: center = Point(r.uniform(offsetx, img.cols - offsetx), r.uniform(offsety + lineLenght, img.rows - offsety)); width = r.uniform(1, min(offsetx, offsety)); height = r.uniform(1, min(offsetx, offsety)); rc = Rect(center-Point(width ,height )/2, center + Point(width , height )/2); rectangle(img,rc, Scalar(i), -1); break; case MyELLIPSE: center = Point(r.uniform(offsetx, img.cols - offsetx), r.uniform(offsety + lineLenght, img.rows - offsety)); width = r.uniform(1, min(offsetx, offsety)); height = r.uniform(1, min(offsetx, offsety)); angle = r.uniform(0, 180); ellipse(img, center,Size(width/2,height/2),angle,0,360, Scalar(i), -1); break; } } return img; }
void Core_ArrayOpTest::run( int /* start_from */) { int errcount = 0; // dense matrix operations { int sz3[] = {5, 10, 15}; MatND A(3, sz3, CV_32F), B(3, sz3, CV_16SC4); CvMatND matA = A, matB = B; RNG rng; rng.fill(A, CV_RAND_UNI, Scalar::all(-10), Scalar::all(10)); rng.fill(B, CV_RAND_UNI, Scalar::all(-10), Scalar::all(10)); int idx0[] = {3,4,5}, idx1[] = {0, 9, 7}; float val0 = 130; Scalar val1(-1000, 30, 3, 8); cvSetRealND(&matA, idx0, val0); cvSetReal3D(&matA, idx1[0], idx1[1], idx1[2], -val0); cvSetND(&matB, idx0, val1); cvSet3D(&matB, idx1[0], idx1[1], idx1[2], -val1); Ptr<CvMatND> matC = cvCloneMatND(&matB); if( A.at<float>(idx0[0], idx0[1], idx0[2]) != val0 || A.at<float>(idx1[0], idx1[1], idx1[2]) != -val0 || cvGetReal3D(&matA, idx0[0], idx0[1], idx0[2]) != val0 || cvGetRealND(&matA, idx1) != -val0 || Scalar(B.at<Vec4s>(idx0[0], idx0[1], idx0[2])) != val1 || Scalar(B.at<Vec4s>(idx1[0], idx1[1], idx1[2])) != -val1 || Scalar(cvGet3D(matC, idx0[0], idx0[1], idx0[2])) != val1 || Scalar(cvGetND(matC, idx1)) != -val1 ) { ts->printf(cvtest::TS::LOG, "one of cvSetReal3D, cvSetRealND, cvSet3D, cvSetND " "or the corresponding *Get* functions is not correct\n"); errcount++; } } RNG rng; const int MAX_DIM = 5, MAX_DIM_SZ = 10; // sparse matrix operations for( int si = 0; si < 10; si++ ) { int depth = (unsigned)rng % 2 == 0 ? CV_32F : CV_64F; int dims = ((unsigned)rng % MAX_DIM) + 1; int i, k, size[MAX_DIM]={0}, idx[MAX_DIM]={0}; vector<string> all_idxs; vector<double> all_vals; vector<double> all_vals2; string sidx, min_sidx, max_sidx; double min_val=0, max_val=0; int p = 1; for( k = 0; k < dims; k++ ) { size[k] = ((unsigned)rng % MAX_DIM_SZ) + 1; p *= size[k]; } SparseMat M( dims, size, depth ); map<string, double> M0; int nz0 = (unsigned)rng % max(p/5,10); nz0 = min(max(nz0, 1), p); all_vals.resize(nz0); all_vals2.resize(nz0); Mat_<double> _all_vals(all_vals), _all_vals2(all_vals2); rng.fill(_all_vals, CV_RAND_UNI, Scalar(-1000), Scalar(1000)); if( depth == CV_32F ) { Mat _all_vals_f; _all_vals.convertTo(_all_vals_f, CV_32F); _all_vals_f.convertTo(_all_vals, CV_64F); } _all_vals.convertTo(_all_vals2, _all_vals2.type(), 2); if( depth == CV_32F ) { Mat _all_vals2_f; _all_vals2.convertTo(_all_vals2_f, CV_32F); _all_vals2_f.convertTo(_all_vals2, CV_64F); } minMaxLoc(_all_vals, &min_val, &max_val); double _norm0 = norm(_all_vals, CV_C); double _norm1 = norm(_all_vals, CV_L1); double _norm2 = norm(_all_vals, CV_L2); for( i = 0; i < nz0; i++ ) { for(;;) { for( k = 0; k < dims; k++ ) idx[k] = (unsigned)rng % size[k]; sidx = idx2string(idx, dims); if( M0.count(sidx) == 0 ) break; } all_idxs.push_back(sidx); M0[sidx] = all_vals[i]; if( all_vals[i] == min_val ) min_sidx = sidx; if( all_vals[i] == max_val ) max_sidx = sidx; setValue(M, idx, all_vals[i], rng); double v = getValue(M, idx, rng); if( v != all_vals[i] ) { ts->printf(cvtest::TS::LOG, "%d. immediately after SparseMat[%s]=%.20g the current value is %.20g\n", i, sidx.c_str(), all_vals[i], v); errcount++; break; } } Ptr<CvSparseMat> M2 = (CvSparseMat*)M; MatND Md; M.copyTo(Md); SparseMat M3; SparseMat(Md).convertTo(M3, Md.type(), 2); int nz1 = (int)M.nzcount(), nz2 = (int)M3.nzcount(); double norm0 = norm(M, CV_C); double norm1 = norm(M, CV_L1); double norm2 = norm(M, CV_L2); double eps = depth == CV_32F ? FLT_EPSILON*100 : DBL_EPSILON*1000; if( nz1 != nz0 || nz2 != nz0) { errcount++; ts->printf(cvtest::TS::LOG, "%d: The number of non-zero elements before/after converting to/from dense matrix is not correct: %d/%d (while it should be %d)\n", si, nz1, nz2, nz0 ); break; } if( fabs(norm0 - _norm0) > fabs(_norm0)*eps || fabs(norm1 - _norm1) > fabs(_norm1)*eps || fabs(norm2 - _norm2) > fabs(_norm2)*eps ) { errcount++; ts->printf(cvtest::TS::LOG, "%d: The norms are different: %.20g/%.20g/%.20g vs %.20g/%.20g/%.20g\n", si, norm0, norm1, norm2, _norm0, _norm1, _norm2 ); break; } int n = (unsigned)rng % max(p/5,10); n = min(max(n, 1), p) + nz0; for( i = 0; i < n; i++ ) { double val1, val2, val3, val0; if(i < nz0) { sidx = all_idxs[i]; string2idx(sidx, idx, dims); val0 = all_vals[i]; } else { for( k = 0; k < dims; k++ ) idx[k] = (unsigned)rng % size[k]; sidx = idx2string(idx, dims); val0 = M0[sidx]; } val1 = getValue(M, idx, rng); val2 = getValue(M2, idx); val3 = getValue(M3, idx, rng); if( val1 != val0 || val2 != val0 || fabs(val3 - val0*2) > fabs(val0*2)*FLT_EPSILON ) { errcount++; ts->printf(cvtest::TS::LOG, "SparseMat M[%s] = %g/%g/%g (while it should be %g)\n", sidx.c_str(), val1, val2, val3, val0 ); break; } } for( i = 0; i < n; i++ ) { double val1, val2; if(i < nz0) { sidx = all_idxs[i]; string2idx(sidx, idx, dims); } else { for( k = 0; k < dims; k++ ) idx[k] = (unsigned)rng % size[k]; sidx = idx2string(idx, dims); } eraseValue(M, idx, rng); eraseValue(M2, idx); val1 = getValue(M, idx, rng); val2 = getValue(M2, idx); if( val1 != 0 || val2 != 0 ) { errcount++; ts->printf(cvtest::TS::LOG, "SparseMat: after deleting M[%s], it is =%g/%g (while it should be 0)\n", sidx.c_str(), val1, val2 ); break; } } int nz = (int)M.nzcount(); if( nz != 0 ) { errcount++; ts->printf(cvtest::TS::LOG, "The number of non-zero elements after removing all the elements = %d (while it should be 0)\n", nz ); break; } int idx1[MAX_DIM], idx2[MAX_DIM]; double val1 = 0, val2 = 0; M3 = SparseMat(Md); minMaxLoc(M3, &val1, &val2, idx1, idx2); string s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims); if( val1 != min_val || val2 != max_val || s1 != min_sidx || s2 != max_sidx ) { errcount++; ts->printf(cvtest::TS::LOG, "%d. Sparse: The value and positions of minimum/maximum elements are different from the reference values and positions:\n\t" "(%g, %g, %s, %s) vs (%g, %g, %s, %s)\n", si, val1, val2, s1.c_str(), s2.c_str(), min_val, max_val, min_sidx.c_str(), max_sidx.c_str()); break; } minMaxIdx(Md, &val1, &val2, idx1, idx2); s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims); if( (min_val < 0 && (val1 != min_val || s1 != min_sidx)) || (max_val > 0 && (val2 != max_val || s2 != max_sidx)) ) { errcount++; ts->printf(cvtest::TS::LOG, "%d. Dense: The value and positions of minimum/maximum elements are different from the reference values and positions:\n\t" "(%g, %g, %s, %s) vs (%g, %g, %s, %s)\n", si, val1, val2, s1.c_str(), s2.c_str(), min_val, max_val, min_sidx.c_str(), max_sidx.c_str()); break; } } ts->set_failed_test_info(errcount == 0 ? cvtest::TS::OK : cvtest::TS::FAIL_INVALID_OUTPUT); }
namespace Graphics { using namespace Shaders; int scw, sch; bool haveFBO = false; bool noWarpFX = false; /* Other files can use: namespace Matrices { void SetProjectionMatrix ( const matrix2x3& m ); void SetViewMatrix ( const matrix2x3& m ); void SetModelMatrix ( const matrix2x3& m ); const matrix2x3& CurrentMatrix (); const matrix2x3& ProjectionMatrix (); const matrix2x3& ViewMatrix (); const matrix2x3& ModelMatrix (); } */ namespace Matrices { static matrix2x3 projectionMatrix; static matrix2x3 viewMatrix; static matrix2x3 modelMatrix; static matrix2x3 mvpMatrix; static void LoadMatrix ( const matrix2x3& m ) { GLfloat array[16]; m.FillOpenGLMatrix(array); glLoadMatrixf(array); } void SetProjectionMatrix ( const matrix2x3& m ) { projectionMatrix = m; } void SetViewMatrix ( const matrix2x3& m ) { viewMatrix = m; } // the state is only guaranteed after a SetModelMatrix call void SetModelMatrix ( const matrix2x3& m ) { modelMatrix = m; mvpMatrix = modelMatrix * viewMatrix * projectionMatrix; LoadMatrix(mvpMatrix); } const matrix2x3& CurrentMatrix () { return mvpMatrix; } const matrix2x3& ProjectionMatrix () { return projectionMatrix; } const matrix2x3& ViewMatrix () { return viewMatrix; } const matrix2x3& ModelMatrix () { return modelMatrix; } } void Init ( int w, int h, bool fullscreen ) { SDL_InitSubSystem ( SDL_INIT_VIDEO ); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute ( SDL_GL_ALPHA_SIZE, 0 ); SDL_GL_SetAttribute ( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute ( SDL_GL_DEPTH_SIZE, 24 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 4 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute ( SDL_GL_SWAP_CONTROL, 1 ); Uint32 flags = SDL_OPENGL; if (fullscreen) flags |= SDL_FULLSCREEN; if (!SDL_SetVideoMode(w, h, 0, flags)) { SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLESAMPLES, 0 ); SDL_GL_SetAttribute ( SDL_GL_MULTISAMPLEBUFFERS, 0 ); LOG("Graphics", LOG_WARNING, "Card does not support FSAA!"); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_WARNING, "Card does not support normal video options!"); SDL_GL_SetAttribute ( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute ( SDL_GL_BLUE_SIZE, 5 ); if (!SDL_SetVideoMode(w, h, 0, flags)) { LOG("Graphics", LOG_ERROR, "Bad graphics driver."); abort(); } } } scw = w; sch = h; glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glDepthMask(GL_FALSE); glEnable ( GL_BLEND ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glClearDepth(1.0); glDepthFunc(GL_LESS); glCullFace(GL_CCW); // glEnable ( GL_LINE_SMOOTH ); glEnable ( GL_POINT_SMOOTH ); glHint ( GL_LINE_SMOOTH_HINT, GL_NICEST ); glHint ( GL_POINT_SMOOTH_HINT, GL_NICEST ); #ifdef __MACH__ glHint ( GL_TRANSFORM_HINT_APPLE, GL_FASTEST ); #endif const GLfloat projectionMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.001f, 0.0f, 0.0f, 0.0f, -0.5f, 1.0f }; glMatrixMode(GL_PROJECTION); glLoadMatrixf(projectionMatrix); glMatrixMode(GL_MODELVIEW); glEnableClientState ( GL_VERTEX_ARRAY ); const char* extensions = (const char*)glGetString(GL_EXTENSIONS); const char* renderer = (const char*)glGetString(GL_RENDERER); haveFBO = strstr(extensions, "GL_EXT_framebuffer_object"); noWarpFX = strstr(renderer, "Intel"); } unsigned ToInt ( const std::string& value ) { return atoi(value.c_str()); } bool ToBool ( const std::string& value ) { return value == "true"; } // [WIP] [ADAM] void Reset () { // SDL_SetVideoMode(ToInt(Preferences::Get("Screen/Width")), ToInt(Preferences::Get("Screen/Height")), 0, SDL_ResizeEvent); // these two lines work: // glDeleteFramebuffersEXT(1, &warpFBO); // warpFBO = 0; // SetProjectionMatrix( matrix2x3::Ortho(left, right, bottom, top) ); // what are left, right, bottom, top? } static bool texturingEnabled = false; static void EnableTexturing () { if (!texturingEnabled) { glEnableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = true; } } static void DisableTexturing () { if (texturingEnabled) { glDisableClientState ( GL_TEXTURE_COORD_ARRAY ); texturingEnabled = false; } } static bool blendingEnabled = true; static void EnableBlending () { if (!blendingEnabled) { glEnable(GL_BLEND); blendingEnabled = true; } } static void DisableBlending () { if (blendingEnabled) { glDisable(GL_BLEND); blendingEnabled = false; } } static void SetColour ( const colour& col ) { if (sizeof(col) == sizeof(float) * 4) { glColor4fv((const GLfloat*)&col); } else { glColor4f(col.red(), col.green(), col.blue(), col.alpha()); } } static void ClearColour () { const uint32_t white = 0xFFFFFFFF; glColor4ubv((const GLubyte*)&white); } vec2 SpriteDimensions ( const std::string& sheetname ) { SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } assert(sheet); return vec2(sheet->TileSizeX(), sheet->TileSizeY()); } void DrawSprite ( const std::string& sheetname, int sheet_x, int sheet_y, vec2 position, vec2 size, float rotation, colour col ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); ClearColour(); SetColour(col); SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } Matrices::SetViewMatrix(matrix2x3::Translate(position)); Matrices::SetModelMatrix(matrix2x3::Identity()); if (sheet->IsRotational()) { assert(sheet_x == 0); assert(sheet_y == 0); sheet->DrawRotation(size, rotation); } else { glRotatef(RAD2DEG(rotation), 0.0f, 0.0f, 1.0f); sheet->Draw(sheet_x, sheet_y, size); } } void DrawSpriteFrame ( const std::string& sheetname, vec2 position, vec2 size, int index, float rotation, colour col ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); ClearColour(); SetColour(col); SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } Matrices::SetViewMatrix(matrix2x3::Translate(position)); Matrices::SetModelMatrix(matrix2x3::Identity()); glRotatef(RAD2DEG(rotation), 0.0f, 0.0f, 1.0f); int x = index % sheet->SheetTilesX(); int y = (index - x) / sheet->SheetTilesX(); sheet->Draw(x, y, size); } /* [ADAMLATER] - this is a function that allows sprites to be tiled if necessary void DrawSpriteTile ( const std::string& sheetname, int sheet_x, int sheet_y, vec2 position, vec2 size, float rotation, colour col ) { SetShader("Sprite"); EnableTexturing(); EnableBlending(); ClearColour(); SetColour(col); SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { // load it sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } else { sheet = iter->second; } Matrices::SetViewMatrix(matrix2x3::Translate(position)); Matrices::SetModelMatrix(matrix2x3::Identity()); if (sheet->IsRotational()) { assert(sheet_x == 0); assert(sheet_y == 0); sheet->DrawRotation(size, rotation); } else { glRotatef(RAD2DEG(rotation), 0.0f, 0.0f, 1.0f); sheet->Draw(sheet_x, sheet_y, size); } }*/ const int MAX_TEXTURE_SIZE = 4096; // splits regardless of words int imperfectSplit ( vec2 dims, std::string* bob, int maxSize ) { // bob needs to be a std::vector of std::strings, so that I can add however many strings to it // yet to be figured out return 1; } // splits along spaces, dropping the spaces int idealSplit ( vec2 dims, std::string* bob, int maxSize ) { // has yet to be figured out either return 1; } void DrawTextSDL ( const std::string& text, const std::string& font, const char* justify, vec2 position, int height, colour col, float rotation ) { SetShader("Text"); EnableTexturing(); EnableBlending(); SetColour(col); GLuint texID = TextRenderer::TextObject(font, text, height); Matrices::SetViewMatrix(matrix2x3::Translate(position)); Matrices::SetModelMatrix(matrix2x3::Rotation(rotation)); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); vec2 dims = TextRenderer::TextDimensions(font, text, height); // TEMP int xcoord = 0; int ycoord = 0; TTF_Font* fontObject = TextRenderer::GetFont(font, height); if (TTF_SizeUTF8(fontObject, text.c_str(), &xcoord, &ycoord) == 0 && text == "This is as long as a message can be at font 20: not long..") { printf("The text '%s' has dimensions of %d by %d, and a height of %d\n", text.c_str(), xcoord, ycoord, height); } // END TEMP GLfloat textureArray[] = { 0.0f, 0.0f, dims.X(), 0.0f, dims.X(), dims.Y(), 0.0f, dims.Y() }; vec2 halfSize; if (strcmp(justify, "left") == 0) { halfSize = (dims * (height / dims.Y())); GLfloat vertexArray[8] = { 0, halfSize.Y() / 2, halfSize.X(), halfSize.Y() / 2, halfSize.X(), -halfSize.Y() / 2, 0, -halfSize.Y() / 2 }; glVertexPointer(2, GL_FLOAT, 0, vertexArray); } else { halfSize = (dims * (height / dims.Y())) * 0.5f; if (strcmp(justify, "right") == 0) { GLfloat vertexArray[8] = { -halfSize.X(), halfSize.Y() / 2, 0, halfSize.Y() / 2, 0, -halfSize.Y() / 2, -halfSize.X(), -halfSize.Y() / 2 }; glVertexPointer(2, GL_FLOAT, 0, vertexArray); } else { GLfloat vertexArray[8] = { -halfSize.X(), halfSize.Y(), halfSize.X(), halfSize.Y(), halfSize.X(), -halfSize.Y(), -halfSize.X(), -halfSize.Y() }; glVertexPointer(2, GL_FLOAT, 0, vertexArray); } } glTexCoordPointer(2, GL_FLOAT, 0, textureArray); glDrawArrays(GL_QUADS, 0, 4); } void DrawLine ( vec2 coordinate1, vec2 coordinate2, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); float vertices[4] = { coordinate1.X(), coordinate1.Y(), coordinate2.X(), coordinate2.Y() }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 2 ); } static float RandomFloat ( float min, float max ) { float range = max - min; float uniform = rand() / (float)RAND_MAX; float absolute = uniform * range; return absolute + min; } static void RealDrawLightning ( vec2 coordinate1, vec2 coordinate2, float width, float chaos, colour col, bool tailed, RNG& rng ) { if (col.alpha() < 0.2f) return; SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); unsigned long segments = 12; float offsetting = chaos; float* vertices = (float*)alloca(sizeof(float) * 2 * segments); vec2 tangent = (coordinate2 - coordinate1).UnitVector(); vec2 normal = vec2(-tangent.Y(), tangent.X()); normal.X() = -normal.Y(); for (unsigned long i = 0; i < segments; i++) { float delta = ((float)i / (float)(segments - 1)); //This may be only a partial fix. vec2 basePosition = ((coordinate1*(1.0f-delta)) + (coordinate2*delta));// / 2.0f; if (tailed) { delta *= 2.0f; if (delta > 1.0f) delta = 2.0f - delta; } float maxOffset = offsetting * delta; float actualOffset = RandomFloat(-maxOffset, maxOffset); basePosition += normal * actualOffset; vertices[(i*2)+0] = basePosition.X(); vertices[(i*2)+1] = basePosition.Y(); } glVertexPointer(2, GL_FLOAT, 0, vertices); glDrawArrays(GL_LINE_STRIP, 0, segments); } static RNG lightningRNG; static uint32_t lastSeed = 4; void DrawLightning ( vec2 coordinate1, vec2 coordinate2, float width, float chaos, colour col, bool tailed ) { uint32_t newLastSeed = lightningRNG.GetState(); RealDrawLightning(coordinate1, coordinate2, width, chaos, col, tailed, lightningRNG); RNG localRNG(lastSeed); lastSeed = newLastSeed; col.alpha() *= 0.5f; RealDrawLightning(coordinate1, coordinate2, width * 3.0f, chaos, col, tailed, localRNG); } void DrawBox ( float top, float left, float bottom, float right, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); SetColour(col); float quad[8] = { left, top, left, bottom, right, bottom, right, top }; glVertexPointer ( 2, GL_FLOAT, 0, quad ); glDrawArrays ( GL_QUADS, 0, 4 ); if (width != 0) { SetColour(col + colour(0.45, 0.45, 0.45, 0.0)); glLineWidth(width); float vertices[16] = { left, top, right, top, left, top, left, bottom, right, top, right, bottom, left, bottom, right, bottom }; glVertexPointer ( 2, GL_FLOAT, 0, vertices ); glDrawArrays ( GL_LINES, 0, 8 ); } } void DrawCircle ( vec2 centre, float radius, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } glLineWidth(width); Matrices::SetViewMatrix(matrix2x3::Translate(centre)); Matrices::SetModelMatrix(matrix2x3::Scale(radius)); SetColour ( col ); glVertexPointer(2, GL_FLOAT, 0, circlePoints); glDrawArrays(GL_LINE_LOOP, 0, sizeof(circlePoints) / (2 * sizeof(float))); } void DrawTriangle ( const vec2 point1, const vec2 point2, const vec2 point3, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } SetColour(col); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); float real_triangle[6] = { point1.X(), point1.Y(), point2.X(), point2.Y(), point3.X(), point3.Y() }; glVertexPointer(2, GL_FLOAT, 0, real_triangle); glDrawArrays(GL_POLYGON, 0, 3); } void DrawDiamond ( float top, float left, float bottom, float right, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } SetColour(col); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); float diamond[8] = { (right + left) / 2, top, left, (top + bottom) / 2, (right + left) / 2, bottom, right, (top + bottom) / 2 }; glVertexPointer(2, GL_FLOAT, 0, diamond); glDrawArrays(GL_QUADS, 0, 4); } #pragma mark Particle System Functions std::list<ParticleSystem*> particleSystems; void AddParticles ( const std::string& name, unsigned long particleCount, vec2 centre, vec2 velocity, vec2 velocityVariance, vec2 acceleration, float sizeFactor, float lifetime ) { ParticleSystem* ps = new ParticleSystem(name, particleCount, sizeFactor, centre, velocity, velocityVariance, acceleration, lifetime); particleSystems.push_back(ps); } void DrawParticles () { Shaders::SetShader("Particles"); EnableTexturing(); EnableBlending(); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); for (std::list<ParticleSystem*>::iterator iter = particleSystems.begin(); iter != particleSystems.end(); ++iter) { ParticleSystem* ps = *iter; bool isDead = ps->Update(); if (isDead) { std::list<ParticleSystem*>::iterator iterCopy = iter; ++iter; particleSystems.erase(iterCopy); delete ps; if (iter == particleSystems.end()) break; } ps->Draw(); } } void ClearParticles () { for (std::list<ParticleSystem*>::iterator iter = particleSystems.begin(); iter != particleSystems.end(); ++iter) { delete *iter; } particleSystems.clear(); } static vec2 cameraCorner1; static vec2 cameraCorner2; static float cameraRotation; std::vector<Starfield*> starfields; unsigned starfieldNumber; void DrawStarfield ( float depth ) { while (starfields.size() <= starfieldNumber) { starfields.push_back(new Starfield); } SetShader("Starfield"); EnableTexturing(); DisableBlending(); ClearColour(); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfields[starfieldNumber++]->Draw(depth, (cameraCorner1 + cameraCorner2) / 2.0f); } std::map<std::string, Object3D*> objects3d; static Object3D* GetObject3D ( std::string name ) { std::map<std::string, Object3D*>::iterator iter; iter = objects3d.find(name); if (iter == objects3d.end()) { // load the object Object3D* object = new Object3D(name); objects3d.insert(std::make_pair(name, object)); return object; } else { return iter->second; } } void DrawObject3DAmbient ( std::string name, vec2 centre, float scale, float angle, float bank ) { Object3D* obj = GetObject3D(name); EnableTexturing(); DisableBlending(); obj->BindTextures(); //glUniform3f(UniformLocation("Ambient"), ambient.red(), ambient.green(), ambient.blue()); SetShader("3DBase"); glUniform1f(UniformLocation("specularScale"), obj->SpecularScale()); glUniform1f(UniformLocation("shininess"), obj->Shininess()); Matrices::SetViewMatrix(matrix2x3::Translate(centre)); obj->Draw(scale, angle, bank); } float AspectRatio () { return float(scw) / float(sch); } vec2 MapPoint ( vec2 windowCoords ) { matrix2x3 viewProjection ( Matrices::viewMatrix * Matrices::projectionMatrix ); matrix2x3 vpi = viewProjection.Inverse(); vec2 normalisedCoords = vpi * windowCoords; normalisedCoords += vec2(1.0f, 1.0f); normalisedCoords *= 0.5f; return vec2(normalisedCoords.X() * scw, normalisedCoords.Y() * sch); } void DrawPoint ( vec2 coord, float width, colour col ) { SetShader("Primitive"); DisableTexturing(); if (col.alpha() < 1.0f) { EnableBlending(); } else { DisableBlending(); } SetColour(col); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); float quad[8] = { coord.X(), coord.Y(), coord.X(), coord.Y() - 2, coord.X() + 2, coord.Y() - 2, coord.X() + 2, coord.Y() }; glVertexPointer ( 2, GL_FLOAT, 0, quad ); glDrawArrays ( GL_QUADS, 0, 4 ); /* ¡WARNING! IMMEDIATE MODE! ENTER AT YOUR OWN RISK */ // glBegin(GL_POINTS); // glVertex2f(coord.X(), coord.Y()); // glEnd(); } bool IsCulled ( vec2 position, float radius ) { if ((position.X() + radius) < cameraCorner1.X()) return true; if ((position.X() - radius) > cameraCorner2.X()) return true; if ((position.Y() + radius) < cameraCorner1.Y()) return true; if ((position.Y() - radius) > cameraCorner2.Y()) return true; return false; } void SetCamera ( vec2 corner1, vec2 corner2, float rotation ) { matrix2x3 projection ( matrix2x3::Ortho(corner1.X(), corner2.X(), corner1.Y(), corner2.Y()) ); if (fabs(rotation) > 0.00004f) projection *= matrix2x3::Rotation(rotation); Matrices::SetProjectionMatrix(projection); cameraCorner1 = corner1; cameraCorner2 = corner2; } void BeginFrame () { glDepthMask(GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDepthMask(GL_FALSE); Matrices::SetViewMatrix(matrix2x3::Identity()); Matrices::SetModelMatrix(matrix2x3::Identity()); starfieldNumber = 1; } void EndFrame () { #ifdef __MACH__ glSwapAPPLE(); #else SDL_GL_SwapBuffers(); #endif TextRenderer::Prune(); } void BeginWarp ( float magnitude, float angle, float scale ) { #ifndef DISABLE_WARP_EFFECTS if (!haveFBO || noWarpFX) return; warpMag = magnitude; warpAngle = angle; warpScale = scale; if (magnitude < WARP_MAG_THRESHOLD) return; if (warpFBO == 0) { glGenFramebuffersEXT(1, &warpFBO); glGenTextures(1, &warpTex); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warpFBO); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, warpTex); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, scw, sch, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, warpTex, 0); GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); assert(status == GL_FRAMEBUFFER_COMPLETE_EXT); } else { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warpFBO); } glClear(GL_COLOR_BUFFER_BIT); #endif } void EndWarp () { #ifndef DISABLE_WARP_EFFECTS if (!haveFBO || noWarpFX || warpMag < WARP_MAG_THRESHOLD) return; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, warpTex); Shaders::SetShader("DistortWarp"); glUniform1f(Shaders::UniformLocation("Angle"), warpAngle); glUniform1f(Shaders::UniformLocation("Magnitude"), warpMag); glUniform1f(Shaders::UniformLocation("Scale"), 1.0f / warpScale); glUniform2f(Shaders::UniformLocation("Target"), 0.088f, 0.0f); const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; const GLfloat texCoords[] = { 0.0f, 0.0f, scw, 0.0f, scw, sch, 0.0f, sch }; glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); EnableTexturing(); DisableBlending(); glDrawArrays(GL_QUADS, 0, 4); #endif } void PreloadSpriteSheet(const std::string& sheetname) { SpriteSheet* sheet; SheetMap::iterator iter = spriteSheets.find(sheetname); if (iter == spriteSheets.end()) { sheet = new SpriteSheet(sheetname); spriteSheets[sheetname] = sheet; } } void PreloadFont(const std::string& fontname) { TextRenderer::TextDimensions(fontname, "", 2); } }
int main(int argc, char ** argv) { if(argc < 2) { cout << "Usage: " << endl; cout << " TV norm: ./depthInpainting TV depthImage" << endl; cout << " PSNR calc: ./depthInpainting P depthImage mask inpainted" << endl; cout << " Inpainting: ./depthInpainting LRTV depthImage mask outputPath" << endl; cout << " Generating: ./depthInpainting G depthImage missingRate outputMask outputMissing" << endl; cout << " LowRank: ./depthInpainting L depthImahe mask outputpath" << endl; cout << " LRTVPHI: ./depthInpainting LRTVPHI depthImage mask outputPath" << endl; cout << " TVPHI norm: ./depthInpainting TVPHI depthImage" << endl; cout << " LRL0: ./depthInpainting LRL0 depthImage mask outputPath initImage K lambda_L0 MaxIterCnt" << endl; cout << " LRL0PHI: ./depthInpainting LRL0PHI depthImage mask outputPath initImage K lambda_L0 MaxIterCnt" << endl; cout << " L0: /depthInpainting L0 depthImage" << endl; return 0; } string instruction = argv[1]; if( instruction == "TV" ) { Mat img = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); cout << NORM_TV(img) << endl; } if( instruction == "TVPHI") { Mat img = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); LRTVPHI lrttv; lrttv.setShrinkageParam(1.0, 1.0); cout << lrttv.NORM_TVPHI(img) << endl; } else if( instruction == "P" ) { Mat original = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); Mat inpainted = imread(argv[4], CV_LOAD_IMAGE_GRAYSCALE); Mat mask = imread(argv[3], CV_LOAD_IMAGE_GRAYSCALE); cout << PSNR(original, inpainted, mask) << endl; } else if( instruction == "G" ) { string disparityPath = argv[2]; int missingRate = atof(argv[3]); string outputMask = argv[4]; string outputMissing = argv[5]; Mat disparityOriginal = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); int W = disparityOriginal.cols; int H = disparityOriginal.rows; RNG rng; // mask: 0 indicates missing pixels Mat mask = Mat::zeros(H, W, CV_8U); rng.fill(mask, RNG::UNIFORM, 0, 255); threshold(mask, mask, 255 * missingRate / 100, 255, THRESH_BINARY); Mat disparityMissing; multiply(disparityOriginal, mask / 255, disparityMissing); imwrite(outputMask, mask); imwrite(outputMissing, disparityMissing); } // Low rank else if(instruction == "L" ) { string disparityPath = argv[2]; string maskPath = argv[3]; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); string inpaintedPath = argv[4]; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); multiply(disparityMissing, mask / 255, disparityMissing); Mat inpainted = TNNR(disparityMissing, mask, 9, 9, 0.06); imwrite(argv[4], inpainted); } // only TV inpainting else if( instruction == "T" ) { string disparityPath = argv[2]; string maskPath = argv[3]; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); string inpaintedPath = argv[4]; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); multiply(disparityMissing, mask / 255, disparityMissing); // Mat denoised; // inpaint(disparityMissing, 255 - mask, denoised, 11, INPAINT_TELEA); // imwrite(inpaintedPath, denoised); // try our TV // we can use low rank to initialize U_ Mat denoised = imread(argv[5], CV_LOAD_IMAGE_ANYCOLOR); //TNNR(disparityMissing, mask, 9, 9, 0.06); LRTV lrtv(disparityMissing, mask); // rho dt lambda_tv lambda_rank 100 10 lrtv.setParameters(0, 1, 0.01, 0); lrtv.init_U(denoised); lrtv.sub_1(); Mat M = lrtv.getM(); Mat Y = lrtv.getY(); Mat result = lrtv.getU(); Mat output; result.convertTo(output, CV_8UC1); imwrite(inpaintedPath, output); imwrite("M.png", M); imwrite("Y.png", Y); } else if( instruction == "LRTV" ) { string disparityPath = argv[2]; string maskPath = argv[3]; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); string inpaintedPath = argv[4]; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); multiply(disparityMissing, mask / 255, disparityMissing); // Mat denoised; // inpaint(disparityMissing, 255 - mask, denoised, 11, INPAINT_TELEA); // imwrite(inpaintedPath, denoised); // try our TV // we can use low rank to initialize U_ //Mat denoised = TNNR(disparityMissing, mask, 9, 9, 0.06); Mat denoised = imread(argv[5], CV_LOAD_IMAGE_GRAYSCALE); LRTV lrtv(disparityMissing, mask); // rho dt lambda_tv lambda_rank 100 10 lrtv.setParameters(1.2, 0.1, 40, 10); lrtv.init_U(denoised); Mat result = lrtv.compute(); Mat M = lrtv.getM(); Mat Y = lrtv.getY(); Mat output; result.convertTo(output, CV_8UC1); imwrite(inpaintedPath, output); imwrite("M.png", M); imwrite("Y.png", Y); } // for stat else if( instruction == "S" ) { Mat dispU = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); int H = dispU.rows; int W = dispU.cols; Mat disp = Mat::zeros(H, W, CV_32FC1); dispU.convertTo(disp, CV_32FC1); Mat kernelx_plus_ = (Mat_<float>(1,3)<<0.0,-1.0,1.0); Mat kernelx_minus_ = (Mat_<float>(1,3)<<-1.0,1.0,0.0); Mat kernely_plus_ = (Mat_<float>(3,1)<<0.0,-1.0,1.0); Mat kernely_minus_ = (Mat_<float>(3,1)<<-1.0,1.0,0.0); Mat grad_x_plus, grad_x_minus, grad_y_plus, grad_y_minus; filter2D(disp, grad_x_plus, -1, kernelx_plus_); filter2D(disp, grad_x_minus, -1, kernelx_minus_); filter2D(disp, grad_y_plus, -1, kernely_plus_); filter2D(disp, grad_y_minus, -1, kernely_minus_); Mat ux, uy; ux = (grad_x_minus + grad_x_plus) / 2.0; uy = (grad_y_minus + grad_y_plus) / 2.0; pow(ux, 2.0, ux); pow(uy, 2.0, uy); Mat grad; sqrt(ux + uy, grad); Mat r; grad.convertTo(r, CV_8UC1); vector <float> histogram(200,0); for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) { if(r.at<uchar>(i,j) < 200) { int id = r.at<uchar>(i,j); histogram[id] = histogram[id] + 1; } } float total = accumulate(histogram.begin(), histogram.end(), 0.0); fstream file(argv[3],ios::out); int i = 0; for (auto &x : histogram) { i++; cout << x << endl; file << i << " " << x / total << endl; } } else if( instruction == "L0" ) { Mat dispU = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); int H = dispU.rows; int W = dispU.cols; Mat disp = Mat::zeros(H, W, CV_32FC1); dispU.convertTo(disp, CV_32FC1); Mat kernelx_plus_ = (Mat_<float>(1,3)<<0.0,-1.0,1.0); Mat kernelx_minus_ = (Mat_<float>(1,3)<<-1.0,1.0,0.0); Mat kernely_plus_ = (Mat_<float>(3,1)<<0.0,-1.0,1.0); Mat kernely_minus_ = (Mat_<float>(3,1)<<-1.0,1.0,0.0); Mat grad_x_plus, grad_x_minus, grad_y_plus, grad_y_minus; filter2D(disp, grad_x_plus, -1, kernelx_plus_); filter2D(disp, grad_x_minus, -1, kernelx_minus_); filter2D(disp, grad_y_plus, -1, kernely_plus_); filter2D(disp, grad_y_minus, -1, kernely_minus_); Mat ux, uy; ux = (grad_x_minus + grad_x_plus) / 2.0; uy = (grad_y_minus + grad_y_plus) / 2.0; Mat grad; grad = abs(ux) + abs(uy); Mat r; grad.convertTo(r, CV_8UC1); int l0 = 0; for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) { if (grad.at<uchar>(i,j ) <1) l0++; } cout << W*H - l0 << endl; } else if( instruction == "LRTVPHI" ) { string disparityPath = argv[2]; //"../../MiddInpaint/ArtL/disp.png"; string maskPath = argv[3]; //"../../MiddInpaint/ArtL/mask_50.png"; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); string inpaintedPath = argv[4]; //"just_a_test.png"; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); // int H_ = mask.rows; // int W_ = mask.cols; // mask = 255*Mat::ones(H_, W_, CV_8UC1); Mat orig; disparityMissing.copyTo(orig); orig.convertTo(orig, CV_32FC1); multiply(disparityMissing, mask / 255, disparityMissing); imshow("dd",disparityMissing);waitKey(0); LRTVPHI lrttv(disparityMissing, mask); lrttv.setShrinkageParam(1.0,1.0); Mat denoised = imread(argv[5], CV_LOAD_IMAGE_GRAYSCALE); // rho dt lambda_tv lambda_rank // rho = 1.2 lrttv.setParameters(1.2, 0.1, 10, 0.01); lrttv.setNewtonParameters(0.001); // set gamma // imshow("temp", denoised); // waitKey(0);2 lrttv.init_U(denoised); lrttv.init_M(denoised); cout << "optimal objective function value = " << lrttv.sub_1_val(orig) << endl; Mat result; // lrttv.sub_2(); // lrttv.sub_3(); lrttv.sub_1(1.0,10.0); cout << "optimal objective function value = " << lrttv.sub_1_val(orig) << endl; // cout << "OK sub_1" << endl; //Mat result = lrttv.compute(); Mat M = lrttv.getM(); Mat Y = lrttv.getY(); Mat output; result = lrttv.getU(); result.convertTo(output, CV_8UC1); imwrite(inpaintedPath, output); imwrite("tM.png", M); imwrite("tY.png", Y); } else if( instruction == "X" ) { Mat a = (Mat_<float>(2,2)<<0,1,2,3); Mat x; exp(a,x); Mat y; exp(-a,y); Mat result; divide(x-y,x+y,result); cout << result << endl; } else if( instruction == "LRL0" ) { string disparityPath = argv[2]; //"../../MiddInpaint/ArtL/disp.png"; string maskPath = argv[3]; //"../../MiddInpaint/ArtL/mask_50.png"; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); Mat orig; disparityMissing.copyTo(orig); string inpaintedPath = argv[4]; //"just_a_test.png"; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); int K = atoi(argv[6]); float lambda_l0 = atof(argv[7]); int max_iter = atoi(argv[8]); string path1 = argv[9]; multiply(disparityMissing, mask / 255, disparityMissing); Mat denoised = imread(argv[5], CV_LOAD_IMAGE_GRAYSCALE); LRL0 lrl0(disparityMissing, mask); lrl0.setParameters(1.2,0.1,lambda_l0,10); lrl0.init_U(denoised); Mat result = lrl0.compute(K, max_iter, inpaintedPath, orig, path1); // Mat output; //result.convertTo(output, CV_8UC1); //imwrite(inpaintedPath, output); } else if( instruction == "LRL0PHI" ) { string disparityPath = argv[2]; //"../../MiddInpaint/ArtL/disp.png"; string maskPath = argv[3]; //"../../MiddInpaint/ArtL/mask_50.png"; Mat disparityMissing = imread(disparityPath, CV_LOAD_IMAGE_GRAYSCALE); Mat orig; disparityMissing.copyTo(orig); string inpaintedPath = argv[4]; //"just_a_test.png"; Mat mask = imread(maskPath, CV_LOAD_IMAGE_GRAYSCALE); int K = atoi(argv[6]); float lambda_l0 = atof(argv[7]); int max_iter = atoi(argv[8]); string path1 = argv[9]; multiply(disparityMissing, mask / 255, disparityMissing); Mat denoised = imread(argv[5], CV_LOAD_IMAGE_GRAYSCALE); LRL0PHI lrl0phi(disparityMissing, mask); lrl0phi.setParameters(1.2,0.1,lambda_l0,10,0.75); lrl0phi.init_U(denoised); Mat result = lrl0phi.compute(K, max_iter, inpaintedPath, orig, path1); } else { cout << "Argument Error!" << endl; cout << argv[1] << endl; } return 0; }
Genome Species::ReproduceOne(Population& a_Pop, Parameters& a_Parameters, RNG& a_RNG) { Genome t_baby; // for storing the result ////////////////////////// // Reproduction // Spawn only one baby // this tells us if the baby is a result of mating bool t_mated = false; // There must be individuals there.. ASSERT(NumIndividuals() > 0); // for a species of size 1 we can only mutate // NOTE: but does it make sense since we know this is the champ? if (NumIndividuals() == 1) { t_baby = GetIndividual(a_Parameters, a_RNG); t_mated = false; } // else we can mate else { Genome t_mom = GetIndividual(a_Parameters, a_RNG); // choose whether to mate at all // Do not allow crossover when in simplifying phase if ((a_RNG.RandFloat() < a_Parameters.CrossoverRate) && (a_Pop.GetSearchMode() != SIMPLIFYING)) { // get the father Genome t_dad; bool t_interspecies = false; // There is a probability that the father may come from another species if ((a_RNG.RandFloat() < a_Parameters.InterspeciesCrossoverRate) && (a_Pop.m_Species.size()>1)) { // Find different species (random one) // !!!!!!!!!!!!!!!!! // But the different species must have at least one evaluated individual int t_diffspec = 0; int t_giveup = 64; do { t_diffspec = a_RNG.RandInt(0, static_cast<int>(a_Pop.m_Species.size()-1)); } while ((a_Pop.m_Species[t_diffspec].m_AverageFitness == 0) && (t_giveup--)); if (a_Pop.m_Species[t_diffspec].m_AverageFitness == 0) t_dad = GetIndividual(a_Parameters, a_RNG); else t_dad = a_Pop.m_Species[t_diffspec].GetIndividual(a_Parameters, a_RNG); t_interspecies = true; } else { // Mate within species t_dad = GetIndividual(a_Parameters, a_RNG); // The other parent should be a different one // number of tries to find different parent int t_tries = 32; while(((t_mom.GetID() == t_dad.GetID()) || ((!a_Parameters.AllowClones) && (t_mom.CompatibilityDistance(t_dad, a_Parameters) <= 0.00001)) ) && (t_tries--)) { t_dad = GetIndividual(a_Parameters, a_RNG); } t_interspecies = false; } // OK we have both mom and dad so mate them // Choose randomly one of two types of crossover if (a_RNG.RandFloat() < a_Parameters.MultipointCrossoverRate) { t_baby = t_mom.Mate( t_dad, false, t_interspecies, a_RNG); } else { t_baby = t_mom.Mate( t_dad, true, t_interspecies, a_RNG); } t_mated = true; } // don't mate - reproduce the mother asexually else { t_baby = t_mom; t_mated = false; } } /* if (t_baby.HasDeadEnds()) { std::cout << "Dead ends in baby after crossover" << std::endl; // int p; // std::cin >> p; }*/ // OK we have the baby, so let's mutate it. bool t_baby_is_clone = false; if ((!t_mated) || (a_RNG.RandFloat() < a_Parameters.OverallMutationRate)) MutateGenome(t_baby_is_clone, a_Pop, t_baby, a_Parameters, a_RNG); // We have a new offspring now // give the offspring a new ID t_baby.SetID(a_Pop.GetNextGenomeID()); a_Pop.IncrementNextGenomeID(); // sort the baby's genes t_baby.SortGenes(); // clear the baby's fitness t_baby.SetFitness(0); t_baby.SetAdjFitness(0); t_baby.SetOffspringAmount(0); t_baby.ResetEvaluated(); // debug trap /* if (t_baby.NumLinks() == 0) { std::cout << "No links in baby after reproduction" << std::endl; // int p; // std::cin >> p; } if (t_baby.HasDeadEnds()) { std::cout << "Dead ends in baby after reproduction" << std::endl; // int p; // std::cin >> p; } */ return t_baby; }
Spectrum VSDScatteringIntegrator::LiMultiple(const Scene *scene, const Renderer *renderer, const RayDifferential &ray, const Sample *sample, RNG &rng, Spectrum *T, MemoryArena &arena) const { VolumeRegion *vr = scene->volumeRegion; float t0, t1; vr->IntersectP(ray, &t0, &t1); // Do multiple scattering volume integration in _vr_ Spectrum Lv(0.); // Prepare for random walk Spectrum Tr(1.f); Point p = ray(t0), pPrev = ray.o; // printf("%f %f %f, ", p.x, p.y, p.z); int steps = 0; // Sample the events in a random walk // BBox bb = vr->WorldBound(); // printf("%f %f %f & %f %f %f \n", // bb.pMin.x, bb.pMin.y, bb.pMin.z, bb.pMax.x, bb.pMax.y, bb.pMax.z); while(vr->WorldBound().Inside(p)) { //printf("%f %f %f %d \n", p.x, p.y, p.z, steps); steps++; // Sample direction Vector wi = -ray.d, wo; float pdfDirection = 0.f; if(!vr->SampleDirection(p, wi, wo, &pdfDirection, rng)) { // printf("return 1 \n"); return Lv; } Ray r(p, wo, 0); // Sample a distance float pdfDistance = 0.f; float tDist; Point pSample; if(!vr->SampleDistance(r, &tDist, pSample, &pdfDistance, rng)) { // printf("return 2 \n"); return Lv; } // Compute the transmittance pPrev = p; p = r(tDist); Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, r.time, r.depth); Spectrum stepTau = vr->tau(tauRay, .5f * stepSize, rng.RandomFloat()); Tr *= Exp(-stepTau); // Possibly terminate random walk if transmittance is small if (Tr.y() < 1e-3) { const float continueProb = .5f; if (rng.RandomFloat() > continueProb) { Tr = 0.f; // printf("return 3 \n"); break; } Tr /= continueProb; } // Compute emission term at _p_ Lv += Tr * vr->PhotonDensity(p) / (pdfDistance * pdfDirection); } // printf("%f %f %f %d \n", p.x, p.y, p.z, steps); // printf("%d, ", steps); return Lv; }