UnboundLocalError: local variable 'image' referenced before assignment

What I’m trying to do:
I’m trying to send an image from the client to my server and then call a function to process the image and then return an image and display it in an image panel. However, I’m getting the error UnboundLocalError: local variable ‘image’ referenced before assignment.

What I’ve tried and what’s not working:
I’ve tried different ways of sending and obtaining the image but constantly get an error when i try a server call to process the image.

Code Sample:
Client side:

from ._anvil_designer import Form1Template
from anvil import *
import anvil.server
import anvil.media
from anvil import app
global parsed_file_name 

class Form1(Form1Template):

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.uploaded_file = None

    # Any code you write here will run before the form opens.

  def button_1_click(self, **event_args):
    """This method is called when the button is clicked"""
    if not self.uploaded_file:
      return

    parsed_file_name = f"histo.png"
    anvil.server.call("predict_image", parsed_file_name)
    

  def file_loader_1_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader"""
    image_bytes = file.get_bytes()
    image_blob = BlobMedia(content=image_bytes, content_type="image/tif")

    # set image to image box
    self.image_upload.source = image_blob;
    
    file_name = file.name
    parsed_file_name = f"histo.png"
    self.uploaded_file = file
    anvil.server.call("uplink_download",file,parsed_file_name)
    

Server side:

@anvil.server.callable
def uplink_download(media, file_name):
    with open(file_name, 'wb') as f:
        f.write(media.get_bytes())

@anvil.server.callable
def get_png_image(file_name):
    with open(file_name, 'rb') as f:
        return anvil.BlobMedia("image/png", f.read())

@anvil.server.callable
def predict_image(image_bytes):
  #image = Image.open(io.BytesIO(image_bytes.get_bytes()))
  image = data_preprocessing(image, normalized = True)
  with torch.no_grad():
    output = model(image)
  output = torch.sigmoid(output)
  output_np = output.squeeze().cpu().numpy()
  output_img = Image.fromarray((output_np * 255).astype(np.uint8))

  # Convert the image to bytes
  output_bytes = io.BytesIO()
  output_img.save(output_bytes, format='PNG')
  output_bytes.seek(0)  # Move the pointer to the start of the stream

  return output_bytes.getvalue()

Clone link:
share a copy of your app

Hi,

Have a look here:

def predict_image(image_bytes):
#image = Image.open(io.BytesIO(image_bytes.get_bytes()))
image = data_preprocessing(image, normalized = True)

The image variable assignment is commented out but used as a parameter in the next line when you try and pass image as a parameter to data_preprocessing and assigning the value to image again.

2 Likes