Skip to content

Commit

Permalink
[PyAPI] Tensor creation from Pillow
Browse files Browse the repository at this point in the history
  • Loading branch information
akuporos committed Feb 13, 2025
1 parent 494d645 commit 39c8c2f
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/bindings/python/requirements_test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ flake8_pep3101<=2.1.0
flake8_quotes<=3.4.0
mypy
Pep8-naming
pillow
pydocstyle
pytest-forked; sys_platform != 'win32'
pytest-xdist
Expand Down
25 changes: 25 additions & 0 deletions src/bindings/python/src/pyopenvino/core/tensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,31 @@ void regclass_Tensor(py::module m) {
py::arg("begin"),
py::arg("end"));

cls.def(py::init([](py::object& image) {
if (!py::isinstance(image, py::module::import("PIL.Image").attr("Image"))) {
throw py::type_error("Input must be a PIL.Image.Image object");
}
auto np_array = py::module::import("numpy").attr("array")(image);
py::array array = np_array.cast<py::array>();

return Common::object_from_data<ov::Tensor>(array, false);
}),
py::arg("image"),
R"(
Constructs Tensor from a Pillow Image.
:param image: Pillow Image to create the tensor from.
:type image: PIL.Image.Image
:Example:
.. code-block:: python
from PIL import Image
import openvino as ov
img = Image.open("example.jpg")
tensor = ov.Tensor(img)
)");

cls.def("get_element_type",
&ov::Tensor::get_element_type,
R"(
Expand Down
3 changes: 1 addition & 2 deletions src/bindings/python/src/pyopenvino/utils/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,7 @@ py::object from_ov_any(const ov::Any& any) {
std::string property_name = it;
auto mutability = it.get_mutability();
std::string mutability_str;
switch (mutability)
{
switch (mutability) {
case ov::PropertyMutability::RW:
mutability_str = "RW";
break;
Expand Down
16 changes: 16 additions & 0 deletions src/bindings/python/tests/test_runtime/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,3 +640,19 @@ def test_copy_and_deepcopy(copy_func, should_share_data):
assert tensor_copy.data[0, 0] == outlier
else:
assert tensor_copy.data[0, 0] == value


def test_tensor_from_pillow():
from PIL import Image

shape = (224, 224, 3)
numpy_dtype = np.uint8
arr = generate_image(shape).astype(numpy_dtype)
img = Image.fromarray(arr)

tensor = ov.Tensor(img)
assert tensor.shape == shape
assert tensor.element_type == ov.Type(numpy_dtype)
assert isinstance(tensor.data, np.ndarray)
assert tensor.data.dtype == numpy_dtype
assert tensor.data.shape == shape

0 comments on commit 39c8c2f

Please sign in to comment.