2
我使用成像器包的质心,并想出以下功能:快速计算图像(或矩阵)
vector_mc <- function(v) {
round(sum(v * 1:length(v))/sum(v))
}
img_mc <- function(img) {
w <- width(img)
h <- height(img)
# sum of all rows
# note that as.matrix(img) is a matrix of w rows and h columns.
row <- rep(0, w)
col <- rep(0, h)
for (i in 1:h) {
row <- row + as.matrix(img)[, i]
col[i] <- sum(as.matrix(img)[, i])
}
c(vector_mc(row), vector_mc(col))
}
事实证明,它退出慢。有更好的方法吗?
谢谢,ekstroem。通过仅删除重复重铸,速度增益非常好,因为我刚测试了100x100图像。只是想知道你是否还优化“rowSums(IMG)”和“colSums(IMG)”?再次感谢。 – bruin
'rowSums'和'colSums'是基本R的一部分,并且是'apply'的更快版本。他们通常很快。 – ekstroem
噢,谢谢...对不起,我不知道那:( – bruin