前言
应用实例
四叉树索引结构可以快速的在二维空间划分数据 ,下面是一张图片的四叉树结构实例代码,根据图片中心划分,拥有非1:1图片的自适应性
tree.h
class Node {
public: PNG *p; //the upper left pixel Node **children; //pointer to four other node int width; //当前像素区块的宽度 int height; //当前像素区块的高度 bool leaf; //是否是叶子节点,true 代表是叶子节点 int x; //当前像素区块左上角顶点像素的横坐标 int y; //当前像素区块左上角顶点像素的纵坐标 int mean_r; //Rmean int mean_g; //Gmean int mean_b; //Bmean public: int count; Node(); Node(PNG* corner, int input_width, int input_height, int x, int y); Node(Node &other); Node(Node &&other); Node& operator=(Node &other); Node& operator=(Node &&other); ~Node(); void print(); pxl *get_pxl(); }; class Tree {
public: Node *root; //根结点 public: Tree(); ~Tree(); Tree(Tree &other); Tree& operator=(Tree &other); void judge(int threshold); pxl *get_pxl(); void load_png(PNG *png); int internal_judge(Node* n); void internal_build(Node* n); void print(); };
tree.cpp
Node::Node() {
//TODO mean_r = 0; mean_g = 0; mean_b = 0; p = nullptr; width = 0; height = 0; x = 0; y = 0; count = 0; leaf = true; children = nullptr; } Node::Node(PNG* corner, int input_width, int input_height, int x, int y) {
//TODO count = 0; children = new Node*[4]; children[0] = nullptr; children[1] = nullptr; children[2] = nullptr; children[3] = nullptr; mean_r = 0; mean_g = 0; mean_b = 0; if (input_width <= 0 || input_height <= 0) {
p = nullptr; leaf = true; return; } p = corner; width = input_width; height = input_height; this->x = x; this->y = y; if (input_width == 1 && input_height == 1) {
leaf = true; mean_r = corner->get_pxl(x, y)->red; mean_g = corner->get_pxl(x, y)->green; mean_b = corner->get_pxl(x, y)->blue; } else {
leaf = false; } } void Tree::internal_build(Node* n) {
int hw = n->width >> 1; int hh = n->height >> 1; int x = n->x; int y = n->y; if (hw > 0 && hh > 0) {
n->children[0] = new Node(n->p, hw, hh, x, y); if (!n->children[0]->leaf) internal_build(n->children[0]); } if ((n->width - hw) > 0 && hh > 0) {
n->children[1] = new Node(n->p, n->width - hw, hh, x + hw, y); if (!n->children[1]->leaf) internal_build(n->children[1]); } if (hw > 0 && (n->height) > 0) {
n->children[2] = new Node(n->p, hw, n->height - hh, x, hh + y); if (!n->children[2]->leaf) internal_build(n->children[2]); } if ((n->width - hw) > 0 && (n->height - hh) > 0) {
n->children[3] = new Node(n->p, n->width - hw, n->height - hh, x + hw, hh + y); if (!n->children[3]->leaf) internal_build(n->children[3]); } int c = 0; for (int i = 0; i < 4; ++i) {
if (n->children[i]) {
++c; n->mean_r += n->children[i]->mean_r; n->mean_g += n->children[i]->mean_g; n->mean_b += n->children[i]->mean_b; } } n->mean_r /= c; n->mean_g /= c; n->mean_b /= c; } void Tree::load_png(PNG *png) {
//TODO root = new Node(png, png->get_width(), png->get_height(), 0, 0); if (!root->leaf) {
internal_build(root); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217057.html原文链接:https://javaforall.net
