使用spatstat转换图像为点模式报错:Can't interpret X as a point pattern
问题解决:spatstat中as.ppp转换图像为点模式报错
错误原因
你当前的代码将二值图像转为im类对象后直接传给as.ppp(),但as.ppp()无法直接将像素值矩阵解析为点模式——它需要的是前景像素的坐标集合,而非整个图像的像素矩阵。
修正方案
从二值图像中提取所有非零(前景)像素的坐标,再将坐标转换为点模式。以下是两种可行的修正代码:
方法1:直接从pixset提取坐标(更简洁)
利用imager包的coords()函数直接提取pixset类型的二值图像中前景像素的坐标:
library(imager) library(spatstat) # 读取图像并预处理 img <- load.image("C:/Users/yyan2/Documents/Dec 21/F10F.jpg") img_gray <- grayscale(img) threshold <- 0.5 img_thresh <- img_gray > threshold # 提取前景像素坐标 pixel_coords <- coords(img_thresh) x <- pixel_coords$x y <- pixel_coords$y # 创建匹配图像尺寸的窗口 image_window <- owin(xrange = c(1, ncol(img_thresh)), yrange = c(1, nrow(img_thresh))) # 转换为点模式 point_pattern <- as.ppp(data.frame(x = x, y = y), window = image_window)
方法2:从spatstat的im对象提取坐标
如果需要基于你已生成的binary_image(im类)处理,可使用spatstat的which.im()函数提取值为1的像素坐标:
library(imager) library(spatstat) # 读取图像并预处理(保留你原有的步骤) img <- load.image("C:/Users/yyan2/Documents/Dec 21/F10F.jpg") img_gray <- grayscale(img) threshold <- 0.5 img_thresh <- img_gray > threshold binary_image <- as.im(matrix(as.numeric(img_thresh), nrow = nrow(img_thresh), ncol = ncol(img_thresh))) image_window <- owin(c(1, ncol(img_thresh)), c(1, nrow(img_thresh))) # 提取值为1的像素坐标并转换为点模式 pixel_coords <- which.im(binary_image, value = 1) point_pattern <- as.ppp(pixel_coords, window = image_window)
额外注意事项
如果生成的点模式与原图像的上下方向相反(imager的y轴从顶部开始计数,spatstat的y轴从底部开始),可反转y坐标修正:
y <- nrow(img_thresh) - y + 1
内容的提问来源于stack exchange,提问作者user21605328
相关产品推荐
相关产品推荐

