在R中修改图像/3d阵列



我对C非常熟悉,但对R很陌生,并努力确保正确处理数据类型。有没有*apply类型的函数可以代替两个循环来迭代三维数组的前两个维度?

#!/usr/bin/Rscript
#Make sure the "tiff" library is installed:
#  apt-get install libtiff5-dev
#  Rscript - <<< "install.packages('tiff',,'http://www.rforge.net/')"
library( "tiff" )
RGBlack <- readTIFF( "Imaging.tif", all=TRUE )
RGBlack <- RGBlack[[2]]
AdjustPixel <- function(pix, background){
    # Blue is always off
    pix[3] = 0
    #Turn red off if > background
    if( pix[1] < background ){ 
            pix[1] <- 0
    }
    else  {
            pix[1] <- 1
    }
    #I green is > background turn on, and turn off red
    if( pix[ 2] > background ) {
            pix[1] <- 0
            pix[2] <- 1
    }
    else {
            pix[2] <- 0
    }
    return(pix)
}

background <- 10/256
#Doesn't Work
#RGBlack <- array( AdjustPixel( RGBlack[, , ], background ), dim=c(512,512,3))
#Works
for( row in 1:dim(RGBlack)[1] ){
    for( col in 1:dim(RGBlack)[2] ) {
            RGBlack[row, col, ] = AdjustPixel( RGBlack[row, col, ], background )
    }
}

Array()看起来很有希望,但

RGBlack <- array( AdjustPixel( RGBlack[,,] ), dim=c(dim1,dim2,3))

似乎没有对RGBlack进行任何更改。

我是遗漏了什么,还是循环使用了正确的解决方案?

如果readTIFF来自tiff-包,那么它将提供一个三维数组。使用for循环处理if(){}else{}语句将非常缓慢。

我认为这会更快:

使用?tiff::readTIFF中的第一个示例进行一些测试(尽管我没有"背景"值。)

img[ , , 3] <- 0
img[ , , 1] <-  img[,,1] >= background | img[,,2] >= background
img[ , , 2] <- img[,,2] > background 

我认为这应该快得多。R广泛使用"["one_answers"[<-"运算符来访问矩阵、数组、列表和数据帧。您应该多次阅读这些函数的帮助页面,我认为可能甚至十次,因为关于它们还有很多需要了解的内容。

最新更新