This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Python Tutorial: From Krita to PIL / NumPy / OpenCV

Tags: None
(comma "," separated)
saedjubarin
Registered Member
Posts
58
Karma
0
Code: Select all
import cv2
import numpy as np
from PIL import Image

# Ok let's strart by getting the selected layer.
layer = Krita.instance().activeDocument().activeNode()

# For this example we also want to have the document dimensions.
width = Krita.instance().activeDocument().width()
height = Krita.instance().activeDocument().height()

# And let's grab the pixel data from it.
pixeldata = layer.pixelData(0,0,width,height) # the last 4 parameters are used to define a region, x, y, width, height

# Now we can form a PIL Image out of it.
mode = "RGBA" # This is the color mode Krita keeps it's pixel data.
size = (width, height)
pil_image = Image.frombytes(mode, size, pixeldata)

# and it's really easy to turn into a NumPy array:
numpy_image = np.array(pil_image, dtype=np.uint8) # You propably don't even need to specify dtype here.

# and perform all kinds of magical OpenCV trickery on it:
ret, magical_black_and_white_image = cv2.threshold(numpy_image, 128, 255, cv2.THRESH_BINARY)

# Ok, that's about it. Now we just send it back to Krita. But let's make it a PIL Image on the way.
magic_image = Image.fromarray(magical_black_and_white_image, mode)

# But we don't actually want an [i]Image[/i] as much as we want the pixel data.
magicpixel_data = magic_image.tobytes()

# ...which we can then send back to Krita.
layer.setPixelData(magicpixel_data, 0,0,width,height) # the last 4 parameters tell krita how to chop the array of bytes to form the actual image on the layer

# Last, but least, let's refresh krita so that we see our changes.
Krita.instance().activeDocument().refreshProjection()


There you have it. Computer Vision 2019 in your Krita.
saedjubarin
Registered Member
Posts
58
Karma
0
Short version:
Code: Select all
import cv2
import numpy as np
from PIL import Image
l, w, h = Krita.instance().activeDocument().activeNode(), Krita.instance().activeDocument().width(), Krita.instance().activeDocument().height()
p = Image.frombytes("RGBA", (w,h), l.pixelData(0,0,width,height))
r, t = cv2.threshold(np.array(p), 128, 255, cv2.THRESH_BINARY)
l.setPixelData(Image.fromarray(t,"RGBA").tobytes(), 0,0,w,h)
Krita.instance().activeDocument().refreshProjection()
User avatar
tymond
KDE Developer
Posts
240
Karma
5
Thank you! That looks useful for making some kind of advanced filters.
haikassyth
Registered Member
Posts
1
Karma
0
Hello there,

Thanks for sharing code details are very nice. But I don't know which way to write to use this code can you please suggest to me.
Python Tutorial


Bookmarks



Who is online

Registered users: Bing [Bot], claydoh, Evergrowing, Google [Bot], rblackwell