{"id":15083,"date":"2024-05-15T09:01:27","date_gmt":"2024-05-15T13:01:27","guid":{"rendered":"https:\/\/blogs.mathworks.com\/deep-learning\/?p=15083"},"modified":"2024-05-29T14:50:16","modified_gmt":"2024-05-29T18:50:16","slug":"data-type-conversion-between-matlab-and-python-whats-new-in-r2024a","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/deep-learning\/2024\/05\/15\/data-type-conversion-between-matlab-and-python-whats-new-in-r2024a\/","title":{"rendered":"Data Type Conversion Between MATLAB and Python: What\u2019s New in R2024a"},"content":{"rendered":"<h6><\/h6>\r\nWhen combining MATLAB with Python\u00ae to create deep learning workflows, data type conversion between the two frameworks can be time consuming and sometimes perplexing. I 've certainly experimented with figuring out how to make MATLAB data compatible with a Python-based model and vice versa. So, you can understand why I am so excited that there are two new data type conversions introduced in MATLAB R2024a.\r\n<h6><\/h6>\r\n<img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-15362 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/data_types.png\" alt=\"Conversion of data types between MATLAB and Python\" width=\"500\" height=\"133\" \/>\r\n<h6><\/h6>\r\n&nbsp;\r\n<h6><\/h6>\r\nIn the following table you can see the new data type conversions. And it came as no surprise to me that they made the list of <a href=\"https:\/\/blogs.mathworks.com\/matlab\/2024\/03\/26\/matlab-r2024a-has-been-released-here-are-my-favourite-updates\/\">Mike Croucher's favorite R2024a updates<\/a>.\r\n<h6><\/h6>\r\n<table width=\"55%;\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><strong>Python Data Type<\/strong><\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><strong>MATLAB Data Type<\/strong><\/td>\r\n<\/tr>\r\n<tr>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">Pandas DataFrame<\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-15092 aligncenter\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/double_arrow.png\" alt=\"\" width=\"69\" height=\"17\" \/><\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">MATLAB <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/table.html\">table<\/a><\/td>\r\n<\/tr>\r\n<tr>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">Python dictionary<\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><img decoding=\"async\" loading=\"lazy\" class=\"wp-image-15092 aligncenter\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/double_arrow.png\" alt=\"\" width=\"73\" height=\"18\" \/><\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">MATLAB <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/dictionary.html\">dictionary<\/a><\/td>\r\n<\/tr>\r\n<tr>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">Python dictionary<\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\"><img decoding=\"async\" loading=\"lazy\" class=\"wp-image-15095 aligncenter\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/arrow.png\" alt=\"\" width=\"72\" height=\"21\" \/><\/td>\r\n<td style=\"padding: 10px; text-align: left;\" width=\"30%\">MATLAB <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/struct.html\">structure<\/a><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\nPerforming the data type conversions is very easy and you can learn all the details in these documentation topics: <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_external\/python-pandas-dataframes.html\">Use Python Pandas DataFrames in MATLAB<\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_external\/python-dict-variables.html\">Use Python Dictionaries in MATLAB<\/a>. So, in this blog post, instead of showing you the code for all the possible conversions, I am going to walk you through an object detection example and present a use case for converting data from a Python dictionary to a MATLAB structure.\r\n<h6><\/h6>\r\n&nbsp;\r\n<h6><\/h6>\r\n<p style=\"font-size: 20px;\"><strong>Object Detection Example<\/strong><\/p>\r\nThis example calls a PyTorch model from MATLAB to detect objects in the input image. When you call the PyTorch model you want to (1) pass MATLAB data to a format that the model can process and (2) convert the model outputs (Python data type) to a MATLAB data type that can be used in MATLAB for visualization, as shown here, but also as an input to the next steps in your workflow.\r\n<h6><\/h6>\r\n<p style=\"font-size: 16px;\"><strong>Python Environment<\/strong><\/p>\r\nSet up the Python interpreter for MATLAB by using the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/pyenv.html\">pyenv<\/a>\u00a0function.\r\n<pre>pe = pyenv(Version=\".\\env\\Scripts\\python.exe\",ExecutionMode=\"OutOfProcess\");\r\n<\/pre>\r\n<h6><\/h6>\r\n<p style=\"font-size: 16px;\"><strong>Python Code for Object Detection<\/strong><\/p>\r\nThe following Python code is saved in the PT_object_detection.py file, which you can call from MATLAB to perform object detection with a PyTorch model.\r\n<pre class=\"brush: python\" style=\"background-color: white;\">import torch\r\nimport torchvision as vision\r\nimport numpy\r\n\r\ndef loadPTmodel():\r\n    # Initialize model with the best available weights\r\n    weights = vision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT\r\n    model = vision.models.detection.fasterrcnn_resnet50_fpn_v2(weights=weights,box_score_thresh=0.95)\r\n    model.eval()\r\n\r\n    return model, weights\r\n\r\ndef detectPT(img,model,weights):\r\n    # Reshape image and convert to a tensor.\r\n    X = numpy.asarray(img)\r\n    X_torch1 = torch.from_numpy(numpy.copy(X))\r\n    if X_torch1.ndim==3:\r\n      X_torch = torch.permute(X_torch1,(2,0,1))\r\n    elif X_torch1.ndim==4:\r\n      X_torch = torch.permute(X_torch1,(3,2,0,1))\r\n    # Initialize the inference transforms\r\n    preprocess = weights.transforms()\r\n    # Apply inference preprocessing transforms\r\n    batch = [preprocess(X_torch)]\r\n    # Use the model \r\n    if X_torch.ndim==3:\r\n      prediction = model(batch)[0]\r\n    elif X_torch.ndim==4:\r\n      prediction = model(list(batch[0]))\r\n\r\n    return prediction\r\n<\/pre>\r\n<h6><\/h6>\r\n<p style=\"font-size: 16px;\"><strong>Object Detection<\/strong><\/p>\r\nRead the image that you want to use for object detection.\r\n<pre>img_filename = \"testCar.png\";\r\nimg = imread(img_filename);\r\n<\/pre>\r\n<h6><\/h6>\r\nPerform object detection with a PyTorch model using co-execution.\r\n<pre>pyrun(\"from PT_object_detection import loadPTmodel, detectPT\")\r\n[model,weights] = pyrun(\"[a,b] = loadPTmodel()\",[\"a\" \"b\"]);\r\npredictions_pt = pyrun(\"a = detectPT(b,c,d)\",\"a\",b=img,c=model,d=weights);\r\n<\/pre>\r\n<h6><\/h6>\r\nThe output of the object detector is a Python dictionary.\r\n<pre>class(predictions_pt)\r\n<\/pre>\r\n<pre class=\"brush: python\" style=\"background-color: white; border: white;\">ans = 'py.dict'\r\n<\/pre>\r\n<h6><\/h6>\r\n<p style=\"font-size: 16px;\"><strong>Convert Predictions<\/strong><\/p>\r\nConvert the objection detection results from a Python dictionary to a MATLAB structure.\r\n<pre>predictions = struct(predictions_pt)\r\n<\/pre>\r\n<pre class=\"brush: python\" style=\"background-color: white; border: white;\">predictions = struct with fields:\r\n     boxes: [1\u00d71 py.torch.Tensor]\r\n    labels: [1\u00d71 py.torch.Tensor]\r\n    scores: [1\u00d71 py.torch.Tensor]\r\n<\/pre>\r\n<h6><\/h6>\r\nThe data variables in the structure prediction are PyTorch tensors. Convert the variables into MATLAB arrays.\r\n<pre>predictions.boxes = double(predictions.boxes.detach().numpy);\r\npredictions.labels = double(predictions.labels.tolist)';\r\npredictions.scores = double(predictions.scores.tolist)';\r\npredictions\r\n<\/pre>\r\n<pre class=\"brush: python\" style=\"background-color: white; border: white;\">predictions = struct with fields:\r\n     boxes: [4\u00d74 double]\r\n    labels: [4\u00d71 double]\r\n    scores: [4\u00d71 double]\r\n<\/pre>\r\n<h6><\/h6>\r\nThe bounding boxes require further processing to align with the input image.\u00a0 A bounding box is an axis-aligned rectangle defined in spatial coordinates as an <em>M<\/em>x4 numeric matrix with rows of the form [<em>x y w h<\/em>], where:\r\n<ul>\r\n \t<li><em>M <\/em>is the number of axis-aligned rectangles.<\/li>\r\n \t<li><em>x <\/em>and\u00a0y\u00a0specify the upper-left corner of the rectangle.<\/li>\r\n \t<li><em>w <\/em>specifies the width of the rectangle, which is its length along the\u00a0<em>x<\/em>-axis.<\/li>\r\n \t<li><em>h<\/em> specifies the height of the rectangle, which is its length along the <em>y<\/em>-axis.<\/li>\r\n<\/ul>\r\n<pre>predictions.boxes = cat(2,predictions.boxes(:,1:2)+1,predictions.boxes(:,3:4)\/2);\r\n<\/pre>\r\n<h6><\/h6>\r\nGet the class labels. The PyTorch model was trained on the COCO data set.\r\n<pre>class_labels = getClassLabels(predictions.labels);\r\n<\/pre>\r\n<h6><\/h6>\r\n<p style=\"font-size: 16px;\"><strong>Visualization<\/strong><\/p>\r\nCreate the labels associated with each of the detected objects.\r\n<pre>num_box = length(predictions.scores);\r\ncolons = repmat(\": \",[1 num_box]);\r\npercents = repmat(\"%\",[1 num_box]);\r\nclass_labels1 = strcat(class_labels,colons,string(round(predictions.scores'*100)),percents);\r\n<\/pre>\r\n<h6><\/h6>\r\nVisualize the object detection results with annotations.\r\n<pre>figure\r\noutputImage = insertObjectAnnotation(img,...\r\n    \"rectangle\",predictions.boxes,class_labels1,LineWidth=1,Color=\"green\");\r\nimshow(outputImage)\r\n<\/pre>\r\n<h6><\/h6>\r\n<img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-15167 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/car_object_detection.png\" alt=\"\" width=\"346\" height=\"233\" \/>\r\n<h6><\/h6>\r\nSo, you can see the object detection was successful with a high degree of confidence.\r\n<h6><\/h6>","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2024\/05\/data_types.png\" class=\"img-responsive attachment-post-thumbnail size-post-thumbnail wp-post-image\" alt=\"\" decoding=\"async\" loading=\"lazy\" \/><\/div><p>\r\nWhen combining MATLAB with Python\u00ae to create deep learning workflows, data type conversion between the two frameworks can be time consuming and sometimes perplexing. I 've certainly experimented... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2024\/05\/15\/data-type-conversion-between-matlab-and-python-whats-new-in-r2024a\/\">read more >><\/a><\/p>","protected":false},"author":194,"featured_media":15362,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[9,5,39,59,45],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/15083"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/users\/194"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/comments?post=15083"}],"version-history":[{"count":51,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/15083\/revisions"}],"predecessor-version":[{"id":15368,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/15083\/revisions\/15368"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/media\/15362"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/media?parent=15083"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/categories?post=15083"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/tags?post=15083"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}