Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to open png device in loop

Tags:

r

png

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?

like image 561
Herc Avatar asked Dec 30 '12 19:12

Herc


2 Answers

I had this issue while saving plots in a loop also. @Dino Fire gave me a hint, my loop-generated file name contained an illegal character...

Ensure that the file name is legal (look for slashes, ampersands, apostrophes etc.)

like image 162
Alex Avatar answered Oct 22 '22 00:10

Alex


I've had the same problem occur, although not in a loop situation. In my case, it was because I was pointing the .png output to a directory that did not exist.

png('./tweets/graphics/unique words.png', width=12, height=8, units='in', res=300)

Once I created the directory, and referenced it correctly, the error went away and I got my .png image.

like image 20
Dino Fire Avatar answered Oct 22 '22 01:10

Dino Fire