我一直在摆弄R中的一个函数,其中,长话短说,我有一个for
-loop,并且在每一步,我使用保存一个图png
,然后立即readPNG
使我可以提取RGB信息.然后我制作第二个图,然后readPNG
这样我可以比较两个图像的RGB.问题是我png()
在一些循环之后不断收到关于无法启动设备或打开文件进行写入的错误消息(可能只有少数几个循环,或者多达几千个循环) .
这是真正简化的代码,但它有基本要素,并生成错误消息:
testfun<-function(beg,fini)
{
library(png)
setwd("D://mydirectory")
for (i in beg:fini)
{
png("test.png",width=277,height=277) #candidate image
par(mai=c(0,0,0,0))
plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
xaxt="n",yaxt="n",frame.plot=F)
polygon(x=c(10,60,60),y=c(10,10,60),col="red")
graphics.off()
image<-readPNG("test.png")
#code where I get rgb values for original
png("test2.png",width=277,height=277) #candidate image with diferent params
par(mai=c(0,0,0,0))
plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
xaxt="n",yaxt="n",frame.plot=F)
polygon(x=c(10,60,60),y=c(10,10,60),col="blue")
graphics.off()
image<-readPNG("test2.png")
#code where I get rgb values for second image, and compare
}
}
Run Code Online (Sandbox Code Playgroud)
并且错误消息:
Error in png("test.png", width = 277, height = 277) :
unable to start png() device
In addition: Warning messages:
1: In png("test.png", width = 277, height = 277) :
Unable to open file 'test.png' for writing
2: In png("test.png", width = 277, height = 277) : opening device failed
Run Code Online (Sandbox Code Playgroud)
最初我有graphics.off()
,dev.off()
但后来认为可能循环是如此之快,以至于在需要再次打开之前关闭一个设备的速度不够快而且它在某种程度上变得"混乱".我也试过Sys.sleep(0.1)
在每次之后使用graphics.off
,但这也没有帮助.我错过了一些愚蠢而明显的东西,或者这只是一个设备错误?
Din*_*ire 20
我发生了同样的问题,虽然不是在循环情况下.就我而言,这是因为我将.png输出指向一个不存在的目录.
png('./tweets/graphics/unique words.png', width=12, height=8, units='in', res=300)
Run Code Online (Sandbox Code Playgroud)
一旦我创建了目录并正确引用它,错误消失了,我得到了我的.png图像.