设计一个轻量的图像数据结构2

在上一篇设计一个轻量的图像数据结构中,我给了一个轻量的图像数据结构实现。设想比较简单,所以在使用过程中就发现了一些问题,目前主要是数据所有权的转移和释放的时机问题。原方案设想是基于一个数据 owner标记实现的,一个比较明显存在的问题就是在函数调用形参的场景

1
2
3
4
5
6
7
8
9
void test(Image img)
{
    //此时数据owner 为 tmp
    Image tmp = img;

    //处理...

    //结束返回时会触发tmp的析构函数,而此时tmp又恰巧是owner,所以数据就会被释放了,这不符合预期
}

于是想了想,还是采用智能指针的那套思路,引用计数。实际上opencv的mat实现也是给予引用计数的,果然还是需要相信已经经受实践考验的方案,思路也非常简单,就是统计对象被赋值了的次数,赋值一次就+1,而拥有数据的对象销毁一次计数就-1,最后可以通过检查计数是否满足了这已经是最后一个对象,如果满足则完成真正的内存释放。

先贴一个智能指针引用计数原理的简单实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Point                                       
{
public:
	Point(int xVal = 0, int yVal = 0) :x(xVal), y(yVal) { }
	int getX() const { return x; }
	int getY() const { return y; }
	void setX(int xVal) { x = xVal; }
	void setY(int yVal) { y = yVal; }

private:
	int x, y;

};

class U_Ptr                                  
{
private:
	
	friend class SmartPtr;      
	U_Ptr(Point *ptr) :p(ptr), count(1) { }
	~U_Ptr() { delete p; }
	
	int count;   
	Point *p;                                                      
};

class SmartPtr
{
public:
	SmartPtr(Point *ptr) :rp(new U_Ptr(ptr)) { }    
	
	SmartPtr(const SmartPtr &sp) :rp(sp.rp) { ++rp->count; }
	  
	SmartPtr& operator=(const SmartPtr& rhs) {    
		++rhs.rp->count;    
		if (--rp->count == 0)    
			delete rp;
		rp = rhs.rp;
		return *this;
	}
	
	~SmartPtr() {       
		if (--rp->count == 0)   
			delete rp;
		else 
		cout << "还有" << rp->count << "个指针指向基础对象" << endl;
	}
	
private:
        U_Ptr *rp;  
};

借鉴以上思路,再把原方案改造一下

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#ifndef MANGO_CORE_IMAGE_H
#define MANGO_CORE_IMAGE_H

#include "common_data.hpp"
#include <vector>
#include <cassert>
#include <array>

using namespace std;

typedef unsigned short uattr;
typedef unsigned char uchar;
typedef uchar Vec3b[3];
typedef uchar Vec4b[4];
typedef float Vec3f[3];
typedef float Vec4f[4];

#define UNITATTR(id, size) ((uattr)((id << 8) | size))
#define UNITATTR_ID(v) ((uattr)(v >> 8))
#define UNITATTR_SIZE(v) ((uattr)(v & 0x00ff))  //calculate the size of one element


enum IMAGE_TYPE
{
    IMAGE_8UC1 = UNITATTR(0, 1),
    IMAGE_8UC2 = UNITATTR(1, 2),
    IMAGE_8UC3 = UNITATTR(2, 3),
    IMAGE_8UC4 = UNITATTR(3, 4),
    IMAGE_32FC1 = UNITATTR(4, 4),
    IMAGE_32FC2 = UNITATTR(5, 8),
    IMAGE_32FC3 = UNITATTR(6, 12),
    IMAGE_32FC4 = UNITATTR(7, 16)
};

enum BORDER_TYPE
{
    NONE = 0,               ///<不填充
    MIRROR = 1,             ///<默认 镜像, 123 | 321
    CONSTANT = 2,           ///<常数填充,  123 | ccc
    REPLICATE = 3,          ///<边界复制,   123 | 333
};

enum CONVERT_TYPE
{
    RGB2GRAY = 0,
    RGB2BGR = 1,
    RGB2RGBA = 2
};

class Image;

class RePtr
{
private:

    friend class Image;
    RePtr() : count(1) { }
    ~RePtr() {}
    int count;
};

class Image
{
private:
    uchar *ptr_;
    Rect origin_rect_;
    Rect my_rect_;
    uattr unit_type_;
    bool owner_;

    int rows;
    int cols;
    RePtr* re_ptr_;
public:
    Image();

    Image(const Size &size, uattr type);

    Image(const Size &size, uattr type, uchar* data);

    Image(const Image &other);
    Image(const Image &&other);

    Image& operator=(const Image &other);
    Image operator()(const Rect &roi);

    virtual ~Image();

private:
    void Release();
public:
    void Create(const Size &size, uattr type);
    void CopyTo(Image &other) const;
    Image Clone() const;
    Image CopyWithBorder(const size_t border_size,
                         const BORDER_TYPE& border_type = BORDER_TYPE::MIRROR,
                         const std::array<uint8_t, 3>& const_border = {0, 0, 0});

    Image Convert(const CONVERT_TYPE& type) const;
public:
    template<typename E>
    E& At(int x, int y);

    template<typename E>
    E& At(const Point &point);

    template<typename E>
    E* Ptr(int x, int y);

    template<typename E>
    E* Ptr(const Point &point);

    std::uint8_t Channels() const;

    bool IsEmpty() const;

    Size GetSize() const;
};

Image LoadImage(const char* img_path);

int WriteImage(Image img, const char* img_path);

Image ConvertType(Image src, const CONVERT_TYPE& type);


#endif //MANGO_CORE_IMAGE_H

具体实现

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#include "image.hpp"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image/stb_image.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image/stb_image_write.h"

#include <cstring>
#include <iostream>

Image::Image()
{
    ptr_ = nullptr;
    re_ptr_ = new RePtr();
    owner_ = false;
    unit_type_ = 0;
    origin_rect_ = Rect();
    my_rect_ = Rect();
    rows = 0;
    cols = 0;
}

Image::Image(const Size &size, uattr type)
{
    ptr_ = (uchar*)malloc(size.width * size.height * UNITATTR_SIZE(type));
    re_ptr_ = new RePtr();

    assert(ptr_ != nullptr);

    my_rect_ = origin_rect_ = Rect(0, 0, size.width, size.height);
    unit_type_ = type;
    rows = size.height;
    cols = size.width;
}

Image::Image(const Size &size, uattr type, uchar* data)
{
    assert(data != nullptr);
    ptr_ = data;
    re_ptr_ = new RePtr();
    my_rect_ = origin_rect_ = Rect(0, 0, size.width, size.height);
    unit_type_ = type;
    rows = size.height;
    cols = size.width;
}

Image::Image(const Image &other)
{
    ptr_ = other.ptr_;
    re_ptr_ = other.re_ptr_;
    ++re_ptr_->count;
    owner_ = true;
    auto& t = const_cast<Image&>(other);
    t.owner_ = false;
    unit_type_ = other.unit_type_;
    origin_rect_ = other.origin_rect_;
    my_rect_ = other.my_rect_;
    rows = other.rows;
    cols = other.cols;
}

Image::Image(const Image &&other)
{
    ptr_ = other.ptr_;
    re_ptr_ = other.re_ptr_;
    ++re_ptr_->count;
    owner_ = true;
    auto t = const_cast<Image&>(other);
    t.owner_ = false;
    unit_type_ = other.unit_type_;
    origin_rect_ = other.origin_rect_;
    my_rect_ = other.my_rect_;
    rows = other.rows;
    cols = other.cols;
}

Image &Image::operator=(const Image &other)
{
    ++other.re_ptr_->count;
    if (--re_ptr_->count == 0)
    {
        Release();
    }
    re_ptr_ = other.re_ptr_;
    ptr_ = other.ptr_;
    origin_rect_ = other.origin_rect_;
    my_rect_ = other.my_rect_;
    unit_type_ = other.unit_type_;
    owner_ = true;
    auto t = const_cast<Image&>(other);
    t.owner_ = false;
    rows = other.rows;
    cols = other.cols;

    return *this;
}

Image Image::operator()(const Rect &roi)
{
    Image ret = *this;
    ret.owner_ = false;
    this->owner_ = true;
    ret.my_rect_ = roi;

    return ret;
}

void Image::Create(const Size &size, uattr type)
{
    Release();

    ptr_ = (uchar*)malloc(size.width * size.height * UNITATTR_SIZE(type));

    assert(ptr_ != NULL);

    my_rect_ = origin_rect_ = Rect(0, 0, size.width, size.height);
    unit_type_ = type;
    rows = size.height;
    cols = size.width;
}

void Image::Release()
{
    if(re_ptr_->count == 0)
    {
        delete re_ptr_;
        re_ptr_ = nullptr;
        ptr_ = nullptr;
        owner_ = true;
        unit_type_ = 0;
        origin_rect_ = Rect();
        my_rect_ = Rect();
        rows = 0;
        cols = 0;
        if (ptr_)
            free(ptr_);
    }
}

std::uint8_t Image::Channels() const
{
    return UNITATTR_SIZE(unit_type_);
}

bool Image::IsEmpty() const
{
    return  ptr_ == nullptr || rows <= 0 || cols <= 0;
}

Size Image::GetSize() const
{
    return Size(my_rect_.width, my_rect_.height);
}


void Image::CopyTo(Image &other) const
{
    other.Create(my_rect_.size(), unit_type_);

    if (my_rect_.x == 0 && my_rect_.y == 0)
    {
        memcpy(other.ptr_, ptr_, my_rect_.height * my_rect_.width * UNITATTR_SIZE(unit_type_));
        return;
    }

    for (int row = 0; row < other.my_rect_.height; ++row)
        memcpy(other.ptr_ + (UNITATTR_SIZE(unit_type_) * other.my_rect_.width * row), ptr_ + (((origin_rect_.width * (row + my_rect_.y)) + my_rect_.x) * UNITATTR_SIZE(unit_type_)), (UNITATTR_SIZE(unit_type_) * other.my_rect_.width));
}

Image Image::Clone() const
{
    Image copy_img;
    CopyTo(copy_img);
    return  copy_img;
}

 Image::~Image()
{
    if (--re_ptr_->count == 0)
    {
        Release();
    }
}

template<typename E>
E &Image::At(int x, int y)
{
    return *((E*)(&(ptr_[UNITATTR_SIZE(unit_type_)*((origin_rect_.width * (y + my_rect_.y)) + (x + my_rect_.x))])));
}

template<typename E>
E &Image::At(const Point &point)
{
    return At<E>(point.x, point.y);
}

template<typename E>
E *Image::Ptr(int x, int y)
{
    return &At<E>(x, y);
}

template<typename E>
E *Image::Ptr(const Point &point)
{
    return Ptr<E>(point.x, point.y);
}

static IMAGE_TYPE ChannelToType(const int channels)
{
    if(channels == 1)
    {
        return  IMAGE_TYPE::IMAGE_8UC1;
    }else if(channels == 2)
    {
        return IMAGE_TYPE::IMAGE_8UC2;
    }else if(channels == 3)
    {
        return IMAGE_TYPE::IMAGE_8UC3;
    }else if(channels == 4)
    {
        return IMAGE_TYPE::IMAGE_32FC4;
    }else{
        return IMAGE_TYPE::IMAGE_32FC4;
    }
}

Image LoadImage(const char* img_path)
{
    Image matrix;
    assert(img_path != nullptr);
    if(img_path != nullptr)
    {
        int w, h, n;
        w = h = n = 0;
        std::uint8_t *data = stbi_load(img_path, &w, &h, &n, 0);
        if(nullptr != data)
        {
            auto tmp = Image(Size(w, h), ChannelToType(n), data);
            matrix = tmp;
        }
    }
    return matrix;
}

int WriteImage(Image img, const char* img_path)
{
    if(img.IsEmpty() || img_path == nullptr)
    {
        return  -1;
    }
    std::uint8_t* data = img.Ptr<std::uint8_t>(0, 0);
    auto src_size = img.GetSize();
    int  h = src_size.height;
    int  w = src_size.width;
    auto n = img.Channels();

    std::string file_name = std::string(img_path);
    size_t dot_position = file_name.find_last_of(".");
    if (dot_position != std::string::npos)
    {
        std::string file_extension = file_name.substr(dot_position + 1);
        if(file_extension == "jpg" || file_extension == "jpeg" )
        {
            //图片质量范围【0-100】,默认95,与opencv一致
            return stbi_write_jpg(img_path, w, h, n, data, 95);
        }else if(file_extension == "png")
        {
            return stbi_write_png(img_path,w, h, n, data, w * n );
        }else if(file_extension == "bmp")
        {
            return stbi_write_bmp(img_path, w, h, n, data);
        }else
        {
            std::cerr<< "The image format unsupported!!!" << std::endl;
        }
    }
    return -1;
}

Image Image::CopyWithBorder(const size_t border_size,
                            const BORDER_TYPE& border_type,
                            const std::array<uint8_t, 3>& const_border)
{
    if(border_size == 0 || border_type == BORDER_TYPE::NONE)
    {
        return Clone();
    }else
    {
        size_t cols = this->cols;
        size_t rows = this->rows;

        size_t new_cols = cols + border_size * 2;
        size_t new_rows = rows + border_size * 2;
        size_t channel = Channels();
        size_t data_size = (new_cols) * (new_rows) * channel;
        uint8_t* data = new uint8_t[data_size]();

        //拷贝原图像数据
        for(size_t i = 0; i < rows; i++)
        {
            size_t new_i = i + border_size;
            size_t new_start = (new_i * new_cols + border_size) * channel;
            std::memcpy(data + new_start, Ptr<std::uint8_t>(0, i), cols * channel);
        }

        Image img_with_border(Size(new_cols, new_cols), unit_type_, data);

        switch(border_type)
        {
            //默认 镜像, 123 | 321
            case BORDER_TYPE::MIRROR:
            {
                //填充左右两边
                for(int i = border_size; i < new_rows - border_size; i++) // rows in new image
                {
                    //左边
                    for(int left = border_size - 1, right = border_size; left >= 0; left--, right++) //cols in new image
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(left, i)[c] = img_with_border.Ptr<std::uint8_t>(right, i)[c];
                        }
                    }
                    //右边
                    for(int left = new_cols - border_size - 1, right = new_cols - border_size; right < new_cols; left--,right++) //cols
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(right, i)[c] = img_with_border.Ptr<std::uint8_t>(left, i)[c];
                        }
                    }
                }

                //填充上下两边
                for(int top = border_size - 1, bot = border_size; top >= 0; top--, bot++)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>(0, top), img_with_border.Ptr<std::uint8_t>(0, bot), new_cols * channel);
                }
                for(int bot = new_rows - border_size, top = new_rows - border_size - 1; bot < new_rows; bot++, top--)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>(0, bot), img_with_border.Ptr<std::uint8_t>(0, top), new_cols * channel);
                }
                break;
            }
            case BORDER_TYPE::CONSTANT:
            {
                //填充左右两边
                for(int i = border_size; i < new_rows - border_size; i++) // rows
                {
                    for(int left = 0; left < border_size; left++) //cols
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(left, i)[c] = const_border[c];
                        }
                    }
                    for(int right = new_cols - border_size - 1; right < new_cols; right++) //cols
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(right, i)[c] = const_border[c];
                        }
                    }
                }
                //填充上下两边
                for(int i = 0; i < new_cols; i++) //rows
                {
                    for(int c = 0; c < channel; c++)
                    {
                        img_with_border.Ptr<std::uint8_t>(i, 0)[c] = const_border[c];
                    }
                }
                for(int top = 1; top < border_size; top++)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>( 0, top), img_with_border.Ptr<std::uint8_t>(0, 0), new_cols * channel);
                }
                for(int bottom = new_rows - border_size; bottom < new_rows; bottom++)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>(0, bottom), img_with_border.Ptr<std::uint8_t>(0, 0), new_cols * channel);
                }
                break;
            }
            case BORDER_TYPE::REPLICATE:
            {
                //填充左右两边
                for(int i = border_size; i < new_rows - border_size; i++) // rows
                {
                    //左边
                    for(int left = border_size - 1, right = border_size; left >= 0; left--) //cols
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(left, i)[c] = img_with_border.Ptr<std::uint8_t>(right, i)[c];
                        }
                    }
                    //右边
                    for(int left = new_cols - border_size - 1, right = new_cols - border_size; right < new_cols; right++) //cols
                    {
                        for(int c = 0; c < channel; c++)
                        {
                            img_with_border.Ptr<std::uint8_t>(right, i)[c] = img_with_border.Ptr<std::uint8_t>(left, i)[c];
                        }
                    }
                }
                //填充上下两边
                for(int top = 0; top < border_size; top++)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>(0, top), img_with_border.Ptr<std::uint8_t>(0, border_size), new_cols * channel);
                }
                for(int bottom = new_rows - border_size; bottom < new_rows; bottom++)
                {
                    std::memcpy(img_with_border.Ptr<std::uint8_t>(0, bottom), img_with_border.Ptr<std::uint8_t>(0,new_rows - border_size - 1), new_cols * channel);
                }
                break;
            }
        }

        return img_with_border;
    }
}

Image Image::Convert(const CONVERT_TYPE &type) const
{
    return  ConvertType(*this, type);
}

Image Rgb2Gray(Image src)
{
    assert(src.Channels() == 3);
    auto size = src.GetSize();
    int h = size.height;
    int w = size.width;

    Image dst(size, IMAGE_TYPE::IMAGE_8UC1);

    for(int i = 0; i < h; i++)
    {
        for(int j = 0; j < w; j++)
        {
            auto rgb = src.At<Vec3b>(j, i);
            dst.At<std::uint8_t>(j, i) = std::round(rgb[0] * 0.299 + rgb[1] * 0.578 + rgb[2] * 0.114);
        }
    }
    return dst;
}

Image Rgb2Bgr(Image src)
{
    assert(src.Channels() == 3);
    auto size = src.GetSize();
    int h = size.height;
    int w = size.width;

    Image dst(size, IMAGE_TYPE::IMAGE_8UC3);
    for(int i = 0; i < h; i++)
    {
        for(int j = 0; j < w; j++)
        {
            auto src_rgb = src.At<Vec3b>(j, i);
            auto dst_rgb = src.At<Vec3b>(j, i);
            dst_rgb[0] = src_rgb[2];
            dst_rgb[1] = src_rgb[1];
            dst_rgb[2] = src_rgb[0];
        }
    }
    return dst;
}

Image Rgb2Rgba(Image src)
{
    assert(src.Channels() == 3);
    auto size = src.GetSize();
    int h = size.height;
    int w = size.width;

    Image dst(size, IMAGE_TYPE::IMAGE_8UC4);
    for(int i = 0; i < h; i++)
    {
        for(int j = 0; j < w; j++)
        {
            auto src_rgb = src.Ptr<std::uint8_t>(j, i);
            auto dst_rgb = dst.Ptr<std::uint8_t>(j, i);
            dst_rgb[0] = src_rgb[0];
            dst_rgb[1] = src_rgb[1];
            dst_rgb[2] = src_rgb[2];
            dst_rgb[3] = 255;
        }
    }
    return dst;
}


Image ConvertType(Image src, const CONVERT_TYPE& type)
{
    if(src.IsEmpty()){return  src;}

    switch (type)
    {
        case CONVERT_TYPE::RGB2BGR:
        {
            return Rgb2Bgr(src);
        }
        case CONVERT_TYPE::RGB2GRAY:
        {
            return Rgb2Gray(src);
        }
        case CONVERT_TYPE::RGB2RGBA:
        {
            return Rgb2Rgba(src);
        }
        default:
    }
    return src;
}

这次贴的代码除了解决这个设计问题以外,还补充了一些新的功能,比如图像类型转换等。


微信公众号