Merge Image with Jupyter Notebook To Be One File - image

When we load an image in jupyter notebook , in actual we have two files. Is there a way to merge the both files in single note book file ?
Thank you .

In code cells
When you use code in code cell like below to show an image from an image file inside a notebook, it will actually get encoded within the notebook in the form of base64:
#use code like below to show images as output line because encodes as Base64 code saved within the notebook file
from IPython.display import Image
Image("<myimage_file>.png")
The easiest way to see that is to run such a cell, save the notebook, and inspect the underlying text of the notebook within a text editor. (This is possible right in Jupyter.)
For the corresponding code, you should now see something like this:
"cell_type": "code",
"execution_count": 1,
"id": "72bb5e3d-85c4-4c82-bb18-b466e06b98e7",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUg ...
The ... represents a long string with the image data encoded in base64. Importantly, if you now take that saved notebook and open a new Jupyter session somewhere else where you don't have that image file and you open up the Jupyter notebook, you'll see the image stays visible even without the image file, as long as you don't try to run the code in the cell. If you don't happen to have another computer with Jupyter handy, you can test this by going here and clicking launch binder to spin up a temporary notebook session accessible in your browser from a remote system served by MyBinder.org then dragging and dropping your saved notebook file in the file browser pane on the left side. Double-click to open the notebook and you should see your notebook open and display the image even though the remote system doesn't have your file. If you run the cell though, it isn't going to like the absence of the file, and so the best practice in data management with Jupyter notebook work is to place the notebook(s) and associated files a project folder and transport the entire directory.
There are ways to go back from base64 to the file, so as long as you have the notebook with the encoding you can regenerate the image, see here which is based on this stackoverflow post to convert the string text to bytes. However, I found that replacing the str.encode(string) part of my suggested code with string.encode(), and according to here that may perhaps be better.
In Markdown cells
Unfortunately, last I knew Markdown cells don't do this behavior and so you have to do additional steps to get an image encoded into the markdown cell of a notebook. It can be done though as discussed at the bottom of this post entitled 'Embedding image in ipython notebook for distribution'. (IPython notebooks are the previous version of what evolved into Jupyter notebooks by adding support for many kernel languages.)
I stored a notebook demonstrating using the outcome of following that process to embed images into markdown code within a notebook here, with some links to what I used to put it together. Looking at the text underlying that notebook in your text editor, you'll see the image code is embedded and by opening it elsewhere, you'll conform that it is portable.
Process to generate such base64 encoded image code I adapted from this answer here to 'embedding image into jupyter notebook and exporting to HTML':
%pip install pillow
image_to_convert = "<your_img_file_name_here>.png"
import base64, io, IPython
from PIL import Image as PILImage
image = PILImage.open(image_to_convert )
output = io.BytesIO()
image.save(output, format='PNG')
encoded_string = base64.b64encode(output.getvalue()).decode()
html = '<img src="data:image/png;base64,{}"/>'.format(encoded_string)
print("COPY THE TEXT BELOW INTO A MARKDOWN CELL:")
print(html)
In relation to placing the image encoded as Base64 into the img tag, I found this very helpful.
Someone posted code here to take base64-encoded images from notebooks and embed them in markdown; however, I haven't tried it yet. I also have tried the early part of this answer under 'How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?' which is another take on this; however, I did test that resulting code there make a smiley when in a markdown cell in a notebook. (In fact you can take the part between parentheses that begins data and paste into the URL bar of your browser and see an image too.)

Related

Images turning green-blackish when passing them to dataloaders

I'm working with fastai, trying to pass some images to a dataloader. The original images are kind of pinkish, but after passing them they appear mostly as green-black (see image in link below):
Original pinkish image (up) and example images (down) after passing them to dataloader, and the code.
The code I've used for the datablock and to show the images is:
example = DataBlock(
blocks=(ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=GrandparentSplitter(),
get_y=parent_label,
item_tfms=Resize(128)) #already tried it without item_tfms just in case, still black-green
dls = example.dataloaders(path)
dls.show_batch(nrows=1, ncols=3)
I tried with .tif and .jpeg images, and both show the same problem. The only thing that comes to my mind is that somewhat somewhere is not reading correctly the color format (RGB according to my original files), or maybe transforming it; but I'm not able to figure it out.
Just in case it's important, I'm working in a Jupyter notebook with a MackBook Air M1.
Thanks!
Irene

How to replace text in Gimp image programatically

As in the title - imagine there is some Gimp .xcf file containing many layers. Part of these layers contain text. Is there any format I can export .xcf file to, that it somehow preserve 'human readable' text ?
The final goal is to process that text and put it again into the file, I am aware that this sounds unusual but maybe some of you have an idea how to achieve scenario like that.
I did some research and I saw I can export image to .psd format and then using NPM package process that image and extract text. This is just partially solves the problem, because I will not know how to put the processed text back into this .psd file (unless I decompile this NPM package and try to write some implementation myself...)
Any solutions and alternatives higly appreciated
You can script Gimp (using Scheme or Python). Technically you cannot change the text in a layer (there is no API for that), but you can recover the characteristics of a text layer (original text, font type, font size...) and recreate a new layer with a new text. Here is some Python code to recover the text information:
def text_info(img,layer):
parasites=None
try:
parasites=layer.parasite_list()
except Exception as e:
pass;
if parasites and 'gimp-text-layer' in parasites:
data=layer.parasite_find('gimp-text-layer').data
pdb.gimp_message('Text layer "%s": %s' % (layer.name,data))
else:
pdb.gimp_message('No text information found for layer "%s"' % layer.name)
(this information is only present of the file has been saved, it is not available on a newly created layer, but this shouldn't bea problem in your case)
Of course if the text is in a plain bitmap layer of its own this cannot be done, you have to guess the font type & size (but sometimes the code above can still recover the text information)
But if your XCF has a simple structure, it can be a lot simpler to decompose it into individual images, and build a new image with ImageMagick, using some of these layers plus new text images (or directly rendered text).

What is the format "BM6"?

I am working with an old system of palletes. When I export an image, it also creates an pallete with 15/16 colors. But when I try to replicate the same result, the program does not recognize the image which I just created. To analyse what happened, I opened some images with notepad and compared them with my "creation" and I noticed quite some differences.
But the most interesting thing was that at the beginning of my images' code was the type "BM6", while they should be "png" or "bmp". I think that is some thing of codification, but I cannot find anything about it.
If the image file is properly formed, then you can take your .bm6 file and simple change / rename the extension to .bmp. And it should suddenly be an image.
.bm6 can result from creating an image file using a text editor, as seen here.

TIFF16 image looks different in windows file viewer and MATLAB

General problem description
I have 33 TIFF16 images and I want to do some processing on them using MATLAB. So reading them is the first step. After I download an image from the web and then try to read it using MATLAB's imread (as well as Tiff and read). I display the image using imshow. The image displayed by the Windows File Viewer and MATLAB is totally different. I cannot process them since I don't trust MATLAB has read them correctly. I give more specifics of the problem now.
EDIT: If it helps, the details of the TIFF16 images are: TIFF (16 bits per channel, ProPhoto RGB color space, lossless compression)
More details:
I download an image a0008-WP_CRW_3959.tif. Destination: Go to this link -> img0008 -> Expert B (In case somebody wants to try, otherwise I have screenshots below).
I read that image in MATLAB using: img=imread('imgFilename.tif','tiff'); imshow(img,[]); or
t = Tiff('imgFilename.tif','r');
imageData = read(t);
imshow(imageData);
Now, I display the snapshots of Windows file viewer:
Next, snapshot of what MATLAB shows me:
Now, I have a good reason to believe that Windows file viewer is correct. Go the same link as previous. Scroll down to img0008. Hover your mouse onto the leftmost img0008. A thumbnail view of Expert B will come which looks same as what Windows shows me.
Does anybody know how to make MATLAB read and show the tiff16 image correctly?
Thank you #MarkRansom for pointing me to the embedded color profile possibility. I believe the following solution is correct and produces the same output as Windows File Viewer.
First read the icc-color-profile using iccread command.
I_rgb = imread('a0008-WP_CRW_3959.tif');
outprof = iccread('sRGB.icm');
P = iccread('a0008-WP_CRW_3959.tif');
Then convert the image into sRGB profile using makecform and applycform:
C = makecform('icc',P,outprof);
I_cmyk = applycform(I_rgb,C);
imwrite(I_cmyk,'pep_cmyk.tif','tif')
info = imfinfo('pep_cmyk.tif');
imshow('pep_cmyk.tif');
The original image saved on disk and the new - pep_cmyk.tif - look exactly the same with Windows file viewer.

Reuse inline image in IPython notebook

Is it possible to create an inline png image, e.g. using matplotlib, and re-using it in a markdown cell (via html) without saving it on hard disk first?
IPython notebook saves inline images in the ipynb file, so the data is available, I wonder if it is also accessible?
One idea is to generate images for pretty slides (cell mode) and to to suppress the slides for image creation.
No it is not possible without saving the image. Using slide mode you can exclude some cells. is is also possible to use slide-mode and not to show the code if you are using custom templates.

Resources