Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f28da86eea0> #38

Open
hdocmsu opened this issue Jul 24, 2022 · 6 comments

Comments

@hdocmsu
Copy link

hdocmsu commented Jul 24, 2022

Hello, I installed and tried the sample code from README.md and experienced the error below. Any suggestion is appreciated.
Thanks!


UnidentifiedImageError Traceback (most recent call last)
/tmp/ipykernel_316921/2729893238.py in
----> 1 get_ipython().run_cell_magic('compare', '', '\nfrom skimage import data\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\n\nimg = data.chelsea()\ngrayscale_img = rgb2gray(img)\n\nplt.imshow(img)\nplt.axis("off")\nplt.show()\n\nplt.imshow(grayscale_img, cmap="gray")\nplt.axis("off")\nplt.show()\n')

~/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2401 with self.builtin_trap:
2402 args = (magic_arg_s, cell)
-> 2403 result = fn(*args, **kwargs)
2404 return result
2405

~/anaconda3/lib/python3.8/site-packages/decorator.py in fun(*args, **kw)
230 if not kwsyntax:
231 args, kw = fix(args, kw, sig)
--> 232 return caller(func, *(extras + args), **kw)
233 fun.name = func.name
234 fun.doc = func.doc

~/anaconda3/lib/python3.8/site-packages/IPython/core/magic.py in (f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):

~/anaconda3/lib/python3.8/site-packages/jupyter_compare_view/sw_cellmagic.py in compare(self, line, cell)
63 imgdata = b64decode(out_images_base64[0])
64 # maybe possible without the PIL dependency?
---> 65 im = Image.open(io.BytesIO(imgdata))
66 height = im.size[1]
67

~/anaconda3/lib/python3.8/site-packages/PIL/Image.py in open(fp, mode, formats)
3121 for message in accept_warnings:
3122 warnings.warn(message)
-> 3123 raise UnidentifiedImageError(
3124 "cannot identify image file %r" % (filename if filename else fp)
3125 )

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f28da86eea0>

@kolibril13
Copy link
Member

kolibril13 commented Jul 24, 2022

Hi @hdocmsu !
Can you provide also the code that you were running?
And further questions:

  1. What OS are you on?
  2. What browser are you using?

And secondly:
Can you once run these two code cells?

import io
from base64 import b64decode

from IPython.core import magic_arguments
from IPython.core.display import HTML
from IPython.core.magic import Magics, cell_magic, magics_class
from IPython.display import display
from IPython.utils.capture import capture_output
from PIL import Image


@magics_class
class SplitViewMagic(Magics):
    @magic_arguments.magic_arguments()
    @magic_arguments.argument(
        "--position",
        "-p",
        default="50%",
        help=("The position where the slider starts"),
    )
    @magic_arguments.argument(
        "--height",
        "-h",
        default="300",
        help=(
            "The height that the widget has. The width will be adjusted automatically. \
             If height is choosen 'auto', the height will be defined by the resolution \
             in vertical direction of the first image."
        ),
    )
    @cell_magic
    def splity(self, line, cell):
        """Saves the png image and calls the splitview canvas"""

        with capture_output(stdout=False, stderr=False, display=True) as result:
            self.shell.run_cell(cell)

        # saves all jupyter output images into the out_images_base64 list
        out_images_base64 = []
        print(f"{out_images_base64 = }")
        for output in result.outputs:
            data = output.data
            print(f"{type(data) = }")
            print(f"{type(list(data.values())[0]) = }")

            if "image/png" in data:
                png_bytes_data = data["image/png"]
                out_images_base64.append(png_bytes_data)
        
        print(f"{len(out_images_base64) = }")

        # get the parameters the configure the widget
        args = magic_arguments.parse_argstring(SplitViewMagic.splity, line)

        slider_position = args.position
        widget_height = args.height

        if widget_height == "auto":
            imgdata = b64decode(out_images_base64[0])
            # maybe possible without the PIL dependency?
            im = Image.open(io.BytesIO(imgdata))
            width, height = im.size
            widget_height = height

        html_code = f"""
        <div class="outer_layer" style="position: relative; padding-top: {int(widget_height)+3}px;"> 
            <div class="juxtapose" data-startingposition="{slider_position}" style="height: {int(widget_height)}px;; width: auto; top: 1%; left: 1%; position: absolute;">
                <img src="data:image/jpeg;base64,{out_images_base64[0]}" />' <img src="data:image/jpeg;base64,{out_images_base64[1]}" />'
            </div>
        </div>
        <script src="https://cdn.knightlab.com/libs/juxtapose/latest/js/juxtapose.min.js"></script>
        <link rel="stylesheet" href="https://cdn.knightlab.com/libs/juxtapose/latest/css/juxtapose.css" />
        """
        display(HTML(html_code))
        
from IPython import get_ipython  # register cell magic

ipy = get_ipython()
ipy.register_magics(SplitViewMagic)

and this in the second cell?

%%splity --position 73% 
import matplotlib.pyplot as plt
import numpy as np

array1 = np.full((15, 30), 10)
array2 = np.random.randint(0, 10, size=(15, 30))
fig, ax1 = plt.subplots(figsize=(5, 10))
ax1.imshow(array1)
fig, ax2 = plt.subplots(figsize=(5, 10))
ax2.imshow(array2)

Output should be:

out_images_base64 = []
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
len(out_images_base64) = 2

@hdocmsu
Copy link
Author

hdocmsu commented Jul 26, 2022

Dear @kolibril13, thanks a lot for your quick response!

Here is the code that I ran on Jupiter lab. The code is identical to the example in README.md.

%%compare  
from skimage import data
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

img = data.chelsea()
grayscale_img = rgb2gray(img)

plt.imshow(img)
plt.axis("off")
plt.show()

plt.imshow(grayscale_img, cmap="gray")
plt.axis("off")
plt.show()

What OS are you on? --> I am using Linux Ubuntu 20x
What browser are you using? I am using Chrome
Here is the output after I ran the two cell:

out_images_base64 = []
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
type(data) = <class 'dict'>
type(list(data.values())[0]) = <class 'str'>
len(out_images_base64) = 2

@christopher-besch
Copy link
Member

christopher-besch commented Jul 30, 2022

This is an issue with your (@kolibril13) way of determining the image height; I never touched that code.

@hdocmsu, could you try manually setting the height using %%compare --height 220? If my suspect is correct, the error should disappear.

@kolibril13, why is this not in the with statement above:

# saves all jupyter output images into the out_images_base64 list
out_images_base64 = []
for output in result.outputs:
data = output.data
if "image/png" in data:
png_bytes_data = data["image/png"]
out_images_base64.append(png_bytes_data)
if len(out_images_base64) < 2:
raise ValueError(
"There need to be at least two images for Jupyter compare_view to work."
)

Shouldn't result be out of scope here?

@hdocmsu
Copy link
Author

hdocmsu commented Jul 31, 2022

thanks for the response @christopher-besch, when i tried "%%compare --hight 220" the error does not show up but I got a blank output.
Screenshot from 2022-07-30 22-40-18

@christopher-besch
Copy link
Member

Then this seems to be an issue with your Jupyter Lab installation. Could you try running some very basic cell that outputs an image?

@hdocmsu
Copy link
Author

hdocmsu commented Jul 31, 2022

the image output is fine from Jupiter lab.
Screenshot from 2022-07-30 22-44-46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants