我是Matlab的新手,需要一些帮助。我有一个分段图像,我想从图像边框中删除背景(或黑色)像素(值== 1)。我已经能够获得我不想要的边框像素的图像蒙版。 interior_blackPixels很有用,但我想摆脱outer_blackPixels,但是,我不知道如何使用我拥有的蒙版(outer_blackPixels)检索没有黑色像素边框的最终图像。到目前为止的代码如下所示:
# download the climate dataset and unzip. I can download and unzip this into my pc. Please suggest me on main codes for improvement
download.file("http://biogeo.ucdavis.edu/data/climate/cmip5/30s/mi85tx50.zip", destfile = "E://ClimateDataOutputs//MIROC-ESM-CHEM_rcp85TX", mode="wb")
unzip("E://ClimateDataOutputs//MIROC-ESM-CHEM_rcp85TX")
# Codes for improvement
# load required packages
require(sp)
require(rgdal)
require(raster)
require(lsr)
require(maptools)
# For Bioclim - Need to project species polygons
projection <- CRS ("+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
polygons <- readShapePoly("F:\\9. Other projects\\All projected maps\\AllP.shp", proj4string = projection)
polygons$BINOMIAL <- as.character(polygons$BINOMIAL)
names=c(polygons$BINOMIAL)
stats_out<- data.frame(matrix(NA, ncol = 4, nrow = 579))
colnames(stats_out)<-c("BINOMIAL", "AAD", "mean", "obs")
stats_out[,1]<-names
# iterate over species polygons
for (i in 1:579) {
poly<-polygons[i,]
print(poly$BINOMIAL)
data_out<-data.frame(matrix(NA, ncol = 1))
colnames(data_out)<-c("MaxTemp2050rcp85_MIROC_ESM_CHEM")`
for (j in 1:12) {
filename<-c(paste("E:\\ClimateDataOutputs\\mi85tx50",j,".tif", sep=""))
##print(filename)
grid<-raster(filename)
##plot(grid)
##plot(poly, add=TRUE)
data<-extract(grid, poly)
data1<-as.data.frame(data)
colnames(data1)<-c("MaxTemp2050rcp85_MIROC_ESM_CHEM")
data_out= rbind(data_out,data1)
}
M<-mean(data_out$MaxTemp2050rcp85_MIROC_ESM_CHEM, na.rm=TRUE)
AAD<-aad(data_out$MaxTemp2050rcp85_MIROC_ESM_CHEM, na.rm=TRUE)
stats_out$AAD[i]<-AAD
stats_out$mean[i]<-M
stats_out$obs[i]<-nrow(data_out)
}
print(stats_out)
write.csv(stats_out, "E://ClimateDataOutputs//MaxTemp2050rcp85_MIROC_ESM_CHEM_AAD.csv")
请注意,我不介意将outer_blackPixels的像素值替换为'0',因为这不会影响我的分析。因此,我希望我的最终形象是这样的:
img = [1 1 1 1 1 1 1 1
1 1 1 1 2 2 2 1
1 1 1 2 2 2 2 1
1 1 1 2 2 2 2 1
1 1 2 2 2 2 2 1
1 1 2 2 2 2 2 1
1 3 3 1 1 1 3 1
1 3 3 1 1 1 3 1
1 3 3 3 3 3 3 1
1 1 1 1 1 1 1 1];
% Get the black pixels image array
blackPixels = (img == 1);
% Obtain the other pixels by negating the black pixels
otherPixels = ~blackPixels
% Get the border black pixels (or mask)
outer_blackPixels = blackPixels & ~imclearborder(blackPixels)
interior_blackPixels = blackPixels & ~outer_blackPixels
任何帮助/建议将不胜感激。谢谢!
答案 0 :(得分:1)
您可以使用bwlabel
来区分1区域。由于此功能仅处理二进制图像,因此您可以使用logical
将img
转换为二进制文件:
L=bwlabel(~logical(img-1),4)
然后只需将边框转换为0:
img(L==L(1))=0
img
=
0 0 0 0 0 0 0 0
0 0 0 0 2 2 2 0
0 0 0 2 2 2 2 0
0 0 0 2 2 2 2 0
0 0 2 2 2 2 2 0
0 0 2 2 2 2 2 0
0 3 3 1 1 1 3 0
0 3 3 1 1 1 3 0
0 3 3 3 3 3 3 0
0 0 0 0 0 0 0 0
答案 1 :(得分:0)