0% found this document useful (0 votes)
13 views5 pages

Strategy-M Python Code (Notepad)

Uploaded by

suhasjoshua2206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Strategy-M Python Code (Notepad)

Uploaded by

suhasjoshua2206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import tkinter as tk

from tkinter import filedialog, messagebox


from PIL import Image, ImageTk
import cv2
from barcode import Code128
from barcode.writer import ImageWriter
import os
import random
import string
from flask import Flask, render_template_string
import threading

# Flask setup
app = Flask(__name__)

# Create the main application window


root = tk.Tk()
root.title("Tooth 3D Dimension Finder")
root.geometry("1150x700")

# Instructions for accurate measurements


instructions = (
"IMPORTANT INSTRUCTIONS:\n\n"
"1. Ensure the images are taken at 5 cm distance from the tooth.\n"
"2. The tooth should be centered in the image.\n"
"3. Use clean, high-quality images.\n"
"4. Provide straight photos of the top, side, and front views.\n"
)

# Fixed pixel-to-mm ratio based on 5 cm camera distance


PIXEL_TO_MM_RATIO = 0.026 # Approximate ratio (1 pixel = 0.026 mm at 5 cm)

# Initialize variables
images = {"Top View": None, "Side View": None, "Front View": None}
dimensions_mm = {"Width (mm)": 0, "Height (mm)": 0, "Depth (mm)": 0}

# Store the dimensions for later use in Flask


flask_results = {}

def show_instructions():
"""Display the instructions for accurate results."""
messagebox.showinfo("Instructions", instructions)

def select_image(view):
"""Select and display an image for the given view."""
global canvas, images
img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png
*.jpeg")])
if img_path:
images[view] = img_path
img = Image.open(img_path)
img.thumbnail((300, 300))
img_tk = ImageTk.PhotoImage(img)
canvas[view].create_image(150, 150, image=img_tk)
canvas[view].image = img_tk

def calculate_dimensions():
"""Calculate the dimensions in mm based on all three views."""
global images, dimensions_mm, PIXEL_TO_MM_RATIO, flask_results
# Check if all three views are uploaded
if not all(images.values()):
messagebox.showerror("Error", "Please upload images for all three views!")
return

for view, img_path in images.items():


# Load image and convert to grayscale
image = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)

# Threshold the image to isolate the tooth


_, thresh = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)

if not contours:
messagebox.showerror("Error", f"No tooth detected in the {view}
image.")
return

# Find the largest contour (tooth)


tooth_contour = max(contours, key=cv2.contourArea)

# Calculate bounding rectangle for the tooth


x, y, w, h = cv2.boundingRect(tooth_contour)

# Convert dimensions to mm using the pixel-to-mm ratio


width_mm = w * PIXEL_TO_MM_RATIO
height_mm = h * PIXEL_TO_MM_RATIO

# Assign dimensions in mm based on the view


if view == "Top View":
dimensions_mm["Width (mm)"] = width_mm
dimensions_mm["Depth (mm)"] = height_mm
elif view == "Side View":
dimensions_mm["Height (mm)"] = height_mm
dimensions_mm["Depth (mm)"] = max(dimensions_mm["Depth (mm)"],
width_mm)
elif view == "Front View":
dimensions_mm["Width (mm)"] = max(dimensions_mm["Width (mm)"],
width_mm)
dimensions_mm["Height (mm)"] = max(dimensions_mm["Height (mm)"],
height_mm)

# Calculate volume of the tooth (approximation as a rectangular prism)


volume_mm3 = (
dimensions_mm["Width (mm)"]
* dimensions_mm["Height (mm)"]
* dimensions_mm["Depth (mm)"]
)

# Store the results for Flask to display


flask_results = {
"Width": dimensions_mm["Width (mm)"],
"Height": dimensions_mm["Height (mm)"],
"Depth": dimensions_mm["Depth (mm)"],
"Volume (cm³)": volume_mm3 / 1000
}
# Generate a URL to display results in Flask
random_string = ''.join(random.choices(string.ascii_letters + string.digits,
k=6))
url = f"http://127.0.0.1:5000/results/{random_string}"

# Generate the barcode


generate_barcode(url)

# Display results
result.set(
f"Width: {dimensions_mm['Width (mm)']:.2f} mm\n"
f"Height: {dimensions_mm['Height (mm)']:.2f} mm\n"
f"Depth: {dimensions_mm['Depth (mm)']:.2f} mm\n\n"
f"Estimated Volume: {volume_mm3/1000:.2f} cm³"
)

def generate_barcode(data):
"""Generate a barcode and save it in the specified folder."""
barcode_class = Code128(data, writer=ImageWriter())
img_path = "C:/Users/suhas/OneDrive/Desktop/STRATEGY-M
PROJECT/Generated_Codes/barcode.png.png"
barcode_class.save(img_path)

# Display barcode in tkinter


barcode_image = Image.open(img_path)
barcode_image.thumbnail((300, 100)) # Adjust size for better display
barcode_img_tk = ImageTk.PhotoImage(barcode_image)

qr_label.config(image=barcode_img_tk)
qr_label.image = barcode_img_tk

def clear_app():
"""Clear the app's canvas, reset dimensions, and retain the barcode."""
global images, dimensions_mm, flask_results

# Clear images
images = {"Top View": None, "Side View": None, "Front View": None}

# Reset dimensions
dimensions_mm = {"Width (mm)": 0, "Height (mm)": 0, "Depth (mm)": 0}

# Reset flask results


flask_results = {}

# Clear canvas
for view in canvas:
canvas[view].delete("all")

# Reset result display


result.set("Width: 0.00 mm\nHeight: 0.00 mm\nDepth: 0.00 mm\n\nEstimated
Volume: 0.00 mm³")

# Keep the barcode image


barcode_image = Image.open("C:/Users/suhas/OneDrive/Desktop/STRATEGY-M
PROJECT/Generated_Codes/barcode.png.png")
barcode_image.thumbnail((300, 100)) # Adjust size for better display
barcode_img_tk = ImageTk.PhotoImage(barcode_image)

qr_label.config(image=barcode_img_tk)
qr_label.image = barcode_img_tk

# Flask route for results display


@app.route('/results/<string:id>', methods=['GET'])
def results(id):
"""Display the results on a webpage."""
if flask_results:
html_content = f"""
<html>
<body>
<h1>Tooth Dimensions and Volume</h1>
<p><strong>Width:</strong> {flask_results['Width']:.2f} mm</p>
<p><strong>Height:</strong> {flask_results['Height']:.2f} mm</p>
<p><strong>Depth:</strong> {flask_results['Depth']:.2f} mm</p>
<p><strong>Volume:</strong> {flask_results['Volume (cm³)']:.2f}
cm³</p>
</body>
</html>
"""
return render_template_string(html_content)
return "Results not available."

# Header label
header = tk.Label(root, text="Tooth 3D Dimension Finder", font=("Arial", 18,
"bold"))
header.pack(pady=10)

# Instruction button
instruction_button = tk.Button(root, text="Show Instructions",
command=show_instructions)
instruction_button.pack(pady=5)

# Canvas frames for images


canvas_frame = tk.Frame(root)
canvas_frame.pack(pady=10)

canvas = {}
for idx, view in enumerate(["Top View", "Side View", "Front View"]):
frame = tk.Frame(canvas_frame)
frame.grid(row=0, column=idx, padx=10)

label = tk.Label(frame, text=view, font=("Arial", 12))


label.pack()

canvas[view] = tk.Canvas(frame, width=300, height=300, bg="lightgrey")


canvas[view].pack(pady=5)

upload_btn = tk.Button(frame, text=f"Upload {view}", command=lambda v=view:


select_image(v))
upload_btn.pack(pady=5)

# Calculate button
calc_btn = tk.Button(root, text="Calculate Dimensions",
command=calculate_dimensions)
calc_btn.pack(pady=10)

# Display results
result = tk.StringVar()
result.set("Width: 0.00 mm\nHeight: 0.00 mm\nDepth: 0.00 mm\n\nEstimated Volume:
0.00 mm³")
result_label = tk.Label(root, textvariable=result, font=("Arial", 12))
result_label.pack(pady=10)

# Barcode display
qr_label = tk.Label(root)
qr_label.pack(pady=10)

# Clear button
clear_button = tk.Button(root, text="Clear All", command=clear_app)
clear_button.pack(pady=5)

# Start Flask in a separate thread


def run_flask():
app.run(debug=True, use_reloader=False)

flask_thread = threading.Thread(target=run_flask)
flask_thread.start()

# Start the Tkinter main loop


root.mainloop()

You might also like