I've been fiddling around with a function in R, where, long story short, I have a for
-loop, and at each step, I save a plot using png
, then immediately readPNG
so that I can extract RGB information. I then make a second plot, then readPNG
this so I can compare the RGB of the two images.
The problem is that I keep getting an error message about being unable to start the png()
device, or to open the file for writing, after a number of loops (can be as few as a handful of loops, or as many as a few thousand).
Here is really simplified code, but it has the bare essentials, and generates the error message:
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
}
}
And the error message:
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
Originally I had graphics.off()
as dev.off()
but then thought maybe the loop was so fast that turning off one device wasn't fast enough before needing to be open again and it was getting 'confused' somehow. I also tried using Sys.sleep(0.1)
after each graphics.off
, but that didn't help either. Am I missing something stupid and obvious, or is this just a device bug?
Rscript
. And, doespng
work with an even more minimal code, e.g. :png("bla.png");plot(1:10);dev.off()
. – Psychogenicpng
device as a go-between? Not usingpng
will solve your issue with it :). – Psychogenicfname=paste("test",beg%%5,".png",sep=""); png(fname,width=277,height=277) #candidate image
so that you are not writing then attempting to read immediately the same file? – Teletypewriter