An optimal algorithm for reconstructing images from binary measurements