對(duì)二維數(shù)據(jù)進(jìn)行邊界拓展
對(duì)二維數(shù)據(jù)處理的時(shí)候,經(jīng)常遇到需要越界的問(wèn)題,比如對(duì)圖像進(jìn)行濾波操作。對(duì)原始數(shù)據(jù)的邊界進(jìn)行拓展,然后使用拓展后的數(shù)據(jù)作處理,可以解決越界的問(wèn)題。根據(jù)拓展出的數(shù)據(jù)的值來(lái)自哪里可以分為多種邊界拓展方式,我們要實(shí)現(xiàn)的是將邊界進(jìn)行奇對(duì)稱拓展。
算法
舉例說(shuō)明什么是奇拓展。比如對(duì)原始二維數(shù)據(jù)向左拓展4列,那么在邊界上向左第一列復(fù)制邊界上向右第一列,在邊界上向左第二列復(fù)制邊界上向右第二列,以此類推。邊界列并沒有被復(fù)制,因?yàn)镃語(yǔ)言中是從0開始計(jì)數(shù)的,所以邊界列是0列,按照0列對(duì)稱拓展就稱為奇對(duì)稱拓展。如果0列被復(fù)制到左拓展的第一列,1列被復(fù)制到向左拓展的第二列,那么這種拓展方式成為偶拓展。
代碼
對(duì)二維數(shù)據(jù)進(jìn)行奇拓展的代碼片段如下:
void?abExtendMemory(unsigned?char?*&imExtData,?unsigned?char?*&imExtOrgData,?
??int?&S,?int?&R,?
??const?int?rows,?const?int?cols,?const?io_byte?*imData,
??const?int?a1Min,?const?int?a1Max,
??const?int?a2Min,?const?int?a2Max)
{
??S?=?cols?+?(a2Max>0??a2Max:0)?-?(a2Min0??a1Max:0)?-?(a1Min0??0:a1Min)*S?-?(a2Min>0??0:a2Min);
??//?copy?current?bi-level?image?to?the?extended?image
??for?(int?r?=?0;?r?<?rows;?r++){
????memcpy(imExtOrgData?+?r*S,?imData+r*cols,?cols*sizeof(io_byte));
??}
}
上面的函數(shù),實(shí)現(xiàn)的是將原始二維數(shù)據(jù)(實(shí)際是一維存儲(chǔ)在內(nèi)存里的)放到一個(gè)新的內(nèi)存塊中存儲(chǔ),新內(nèi)存塊是添加了拓展邊界的內(nèi)存的。
a1min,表示將原數(shù)據(jù)向上拓展(a1min<0? -a1min:0)行數(shù)據(jù)。
a1max,表示將原數(shù)據(jù)向下拓展(a1max>0? a1max:0)行數(shù)據(jù)。
a2min,表示將原數(shù)據(jù)向左拓展(a2min<0?-a2min:0)列數(shù)據(jù)。
a2max,表示將原數(shù)據(jù)向右右拓展(a2max>0?a2max:0)列數(shù)據(jù)。
void?abOddFillExtendMemory(unsigned?char?*imExtData,?unsigned?char?*imExtOrgData,
??const?int?a1Min,?const?int?a1Max,
??const?int?a2Min,?const?int?a2Max,
??const?int?rows,?const?int?cols,
??const?int?S,?const?int?R)
{
??//?vertical?direction
??for?(int?r?=?a1Min;?r?<?0;?r++){
????memcpy(imExtOrgData?+?r*S,?imExtOrgData?-?r*S,?sizeof(io_byte)*cols);
??}
??for?(int?r?=?a1Max;?r?>?0;?r--){
????memcpy(imExtOrgData?+?(rows-1+r)*S,?imExtOrgData?+?(rows-1-r)*S,?sizeof(io_byte)*cols);
??}
??//?horizontal?direction
??if?(a2Min?<?0){
????for?(int?r?=?0;?r?<?R;?r++){
??????for?(int?ct?=?a2Min;?ct?<?0;?ct++){
????????imExtData[r*S+ct-a2Min]?=?imExtData[r*S-ct-a2Min];
??????}
????}
??}
??if?(a2Max?>?0){
????for?(int?r?=?0;?r?<?R;?r++){
??????for?(int?ct?=?a2Max;?ct?>?0;?ct--){
????????imExtData[r*S+cols-(a2Min<0?a2Min:0)+ct-1]?=?imExtData[r*S+cols-(a2Min<0?a2Min:0)-ct-1];
??????}
????}
??}
}
上面的代碼實(shí)現(xiàn)的是,對(duì)拓展出的邊界進(jìn)行數(shù)據(jù)填充,具體填充方式,按照奇對(duì)稱填充規(guī)則實(shí)現(xiàn)。
總結(jié)
二維數(shù)據(jù)的拓展經(jīng)常被使用到,特別是圖像處理中,使用這段代碼,可以減少點(diǎn)開發(fā)時(shí)間。另外,如果想使用其他拓展算法,可以直接將上面第二個(gè)函數(shù)的賦值操作修改成想要的規(guī)則即可。





