import numpy as np
from skimage import io
from skimage.color import rgb2gray
from skimage.measure import regionprops
import matplotlib.pyplot as plt
from skimage.transform import rotate
import base64
from io import BytesIO
# Assuming 'selected_image_base64' is a base64 encoded string
image_data = base64.b64decode(selected_image_base64)
image_data = BytesIO(image_data)
# Reading the image from bytes data
originalIm = io.imread(image_data)
# Convert the image to binary
bw = (originalIm > (255 / 2)).astype('uint8')
# Get the region properties
s = regionprops(bw)
phi = np.linspace(0, 2 * np.pi, 50)
cosphi = np.cos(phi)
sinphi = np.sin(phi)
imarray = []
plotarrayX = []
plotarrayY = []
textarray = []
xbarbarray = []
ybaraarray = []
aa = []
ba = []
# Loop through each region in the region properties object
for region in s:
y0, x0 = region.centroid
a = region.major_axis_length / 2.0
b = region.minor_axis_length / 2.0
orientation = region.orientation
# Rotation matrix
R = np.array([[np.cos(orientation), -np.sin(orientation)],
[np.sin(orientation), np.cos(orientation)]])
# Ellipse coordinates
xy = np.array([a * cosphi, b * sinphi])
xy = np.dot(R, xy)
x = xy[0, :] + x0
y = xy[1, :] + y0
# Condition to proceed with the plotting and mask creation
if region.minor_axis_length > 5 and region.major_axis_length > 60:
YourText = f'Orientation: {region.orientation}\nArea: {a*b*np.pi}'
plotarrayX.append(x)
plotarrayY.append(y)
textarray.append(YourText)
xbarbarray.append(x0)
ybaraarray.append(y0)
aa.append(a)
ba.append(b)
# Create an ellipse mask and rotate it
rr, cc = np.meshgrid(np.arange(originalIm.shape[1]), np.arange(originalIm.shape[0]))
ellipse_mask = ((cc - y0)**2 / b**2 + (rr - x0)**2 / a**2) <= 1
RotateEllipse = rotate(ellipse_mask, np.degrees(orientation), center=(x0, y0), mode='constant', cval=0)
# Get the part of the original image where the ellipse is found
A_cropped = originalIm * RotateEllipse.astype('uint8')
imarray.append(A_cropped)
# Create the new image
new_image = ~bw
new_image = (new_image * 255).astype('uint8')
# Loop through each array in imarray and add it to new_image
for image in imarray:
new_image = np.maximum(new_image, image)
# Plotting
plt.imshow(new_image, cmap='gray')
for i, x in enumerate(plotarrayX):
plt.plot(x, plotarrayY[i], 'r', linewidth=2)
plt.text(xbarbarray[i] - 150, ybaraarray[i], textarray[i], color=[0, 0, 1], fontsize=12)
plt.show()
plt.savefig('my_plot.png')
# Save the resulting image to a file
output_image_path = "/tmp/result_image.png"
io.imsave(output_image_path, new_image)
# Convert the file path to a data URL so it can be displayed in the web browser
import base64
with open('my_plot.png', "rb") as f:
result_image_data_url = "data:image/png;base64," + base64.b64encode(f.read()).decode("utf-8")
# Set the data URL as the value of the 'result_image_path' variable
result_image_path = result_image_data_url