Skip to content

Commit ec9ad99

Browse files
committed
New models, changed sidebar, added option to show/hide scale bar, fixed false appearance of "Unsupported image format" message.
1 parent e8f4c6e commit ec9ad99

File tree

10 files changed

+57
-30
lines changed

10 files changed

+57
-30
lines changed

particleanalyzer/core/Detectron2Loader.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616

1717
class Detectron2Loader:
1818
MODEL_MAPPING = {
19-
"Mask R-CNN X152 (dataset 8)": {
19+
"Mask R-CNN X152 (dataset 9)": {
2020
"config_file": "Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv.yaml",
21-
"weights_file": "cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv_d8.pth",
21+
"weights_file": "cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv_d9.pth",
2222
"config_path": "cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv.yaml",
2323
}
2424
}

particleanalyzer/core/ParticleAnalyzer.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,10 @@ def analyze_image(
160160
sahi_mode: bool,
161161
number_of_bins: int,
162162
show_Feret_diametr: bool,
163+
show_Scale_bar: bool,
163164
outline_color,
164-
show_fillPoly,
165-
show_polylines,
165+
show_fillPoly: bool,
166+
show_polylines: bool,
166167
fill_type_color,
167168
fill_color,
168169
fill_alpha,
@@ -242,7 +243,7 @@ def analyze_image(
242243
return self._create_error_return()
243244

244245
output_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
245-
if scale_selector["scale"]:
246+
if scale_selector["scale"] and show_Scale_bar:
246247
output_image = point_manager.draw_scale_on_image(
247248
output_image, scale_factor_glob, scale, *points_scale
248249
)

particleanalyzer/core/YOLOLoader.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
class YOLOLoader:
66
MODEL_MAPPING = {
7-
"Yolo11 (dataset 8)": "Yolo11_d8_batch64.pt",
8-
"Yolo12 (dataset 8)": "Yolo12_d8_batch64.pt",
7+
"Yolo11 (dataset 9)": "Yolo11_d9_batch30.pt",
8+
"Yolo12 (dataset 9)": "Yolo12_d9_batch30.pt",
99
}
1010

1111
def __init__(self):

particleanalyzer/core/languages.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@
153153
"Основные параметры": "Основные параметры",
154154
"Параметры визуализации": "Параметры визуализации",
155155
"Не поддерживаемый формат изображения.": "Не поддерживаемый формат изображения.",
156+
"Включить отображение масштабной шкалы?": "Включить отображение масштабной шкалы?",
156157
},
157158
"en": {
158159
"Подготовка...": "Initializing...",
@@ -294,6 +295,7 @@
294295
"Основные параметры": "Basic parameters",
295296
"Параметры визуализации": "Visualization Parameters",
296297
"Не поддерживаемый формат изображения.": "Unsupported image format.",
298+
"Включить отображение масштабной шкалы?": "Enable display of scale bar?",
297299
},
298300
"zh-cn": {
299301
"Подготовка...": "初始化中...",
@@ -435,6 +437,7 @@
435437
"Основные параметры": "基本参数",
436438
"Параметры визуализации": "渲染选项",
437439
"Не поддерживаемый формат изображения.": "不支持的图像格式。",
440+
"Включить отображение масштабной шкалы?": "启用比例尺显示吗?",
438441
},
439442
"zh-tw": {
440443
"Подготовка...": "初始化中...",
@@ -583,6 +586,7 @@
583586
"Основные параметры": "基本參數",
584587
"Параметры визуализации": "渲染選項",
585588
"Не поддерживаемый формат изображения.": "不支援的圖像格式。",
589+
"Включить отображение масштабной шкалы?": "啟用比例尺顯示嗎?",
586590
},
587591
}
588592

particleanalyzer/core/tour.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
sahiSettingText: "Для анализа больших изображений (свыше 2000 пикселей) с мелкими или слипшимися частицами рекомендуется включить режим SAHI (Slicing Aided Hyper Inference). Оптимальные параметры включают размер сегментов 200-400 пикселей и перекрытие 10-20% - такие настройки обеспечивают баланс между точностью детекции и производительностью. Уменьшение размера сегментов повышает детализацию анализа, но увеличивает время обработки, в то время как регулировка процента перекрытия помогает улучшить обнаружение частиц в областях стыков сегментов, особенно при неоднородном распределении объектов. Эти параметры особенно важны при работе со сложными изображениями, где требуется высокая точность сегментации.",
3434
solutionSegmentText: "В данном разделе можно настроить разрешение: увеличение этого параметра повышает точность анализа, однако приводит к более длительной обработке.",
3535
numberDetectionsText: "Ограничение количества частиц: уменьшите, если система тормозит, увеличьте для редких частиц на больших площадях. Сначала попробуйте 1000, затем корректируйте.",
36-
binsFeretText: "В этом разделе можно настроить количество бинов гистограммы для анализа распределения частиц — оптимальное значение составляет 10-20 бинов, так как оно обеспечивает четкие и хорошо различимые пики. Также здесь доступна опция отображения диаметров Ферета, которые показывают ориентацию частиц непосредственно на результатах сегментации.",
37-
visualizationSettings: "В данном разделе можно задать параметры визуализации контура и заливки сегментированных частиц.",
36+
binsFeretText: "В этом разделе можно настроить количество бинов гистограммы для анализа распределения частиц — оптимальное значение составляет 10-20 бинов, так как оно обеспечивает четкие и хорошо различимые пики.",
37+
visualizationSettings: "В данном разделе можно задать параметры визуализации контура и заливки сегментированных частиц. Также здесь доступны опция отображения диаметров Ферета, которые показывают ориентацию частиц непосредственно на результатах сегментации, и опция отображения масштабной шкалы в пикселях.",
3838
modelParamsText: "Отлично! Теперь настройте параметры модели.",
3939
buttons: {
4040
next: 'Далее',
@@ -60,8 +60,8 @@
6060
sahiSettingText: "For analyzing large images (over 2000 pixels) with small or overlapping particles, enabling SAHI mode (Slicing Aided Hyper Inference) is recommended. Optimal parameters include segment sizes of 200-400 pixels and 10-20% overlap - these settings provide a balance between detection accuracy and performance. Reducing segment size increases analysis detail but increases processing time, while adjusting the overlap percentage helps improve particle detection in segment junction areas, especially with non-uniform object distribution. These parameters are particularly important when working with complex images requiring high segmentation accuracy.",
6161
solutionSegmentText: "In this section, you can configure the resolution: increasing this parameter improves analysis accuracy but leads to longer processing times.",
6262
numberDetectionsText: "Limit the number of particles: decrease if the system is slow, increase for rare particles in large areas. Start with 1000, then adjust as needed.",
63-
binsFeretText: "In this section, you can configure the number of histogram bins for particle distribution analysis - the optimal value is 10-20 bins, as it provides clear and well-distinguishable peaks. Also available here is the option to display Feret diameters, which show particle orientation directly on the segmentation results.",
64-
visualizationSettings: "In this section you can set the parameters for visualizing the outline and filling of segmented particles.",
63+
binsFeretText: "In this section, you can configure the number of histogram bins for particle distribution analysis - the optimal value is 10-20 bins, as it provides clear and well-distinguishable peaks.",
64+
visualizationSettings: "In this section you can set the parameters for visualizing the outline and fill of segmented particles. Also available here is the option to display Feret diameters, which show the orientation of particles directly on the segmentation results, and the option to display a pixel scale.",
6565
modelParamsText: "Great! Now configure the model parameters.",
6666
buttons: {
6767
next: 'Next',
@@ -87,8 +87,8 @@
8787
sahiSettingText: "分析大型圖像(超過2000像素)且含有微小或重疊粒子時,建議啟用SAHI模式(切片輔助超推論)。最佳參數包括200-400像素的切片大小和10-20%的重疊 - 這些設置在檢測精度和性能之間提供平衡。減小切片尺寸可增加分析細節但會增加處理時間,而調整重疊百分比有助於改善切片連接區域的粒子檢測,特別是在非均勻物體分布情況下。這些參數對於需要高分割精度的複雜圖像處理尤為重要。",
8888
solutionSegmentText: "在本區塊中,您可以配置解析度:提高此參數可改善分析精度,但會導致更長的處理時間。",
8989
numberDetectionsText: "限制粒子數量:系統運行緩慢時減少,大面積稀有粒子時增加。先從1000開始,然後根據需要調整。",
90-
binsFeretText: "在本區塊中,您可以配置用於粒子分布分析的直方圖區間數 - 最佳值為10-20個區間,因其能提供清晰且易於區分的峰值。此處還提供顯示Feret直徑的選項,可直接在分割結果上顯示粒子方向。",
91-
visualizationSettings: "在本節中,您可以設定可視化分段粒子輪廓和填充的參數。",
90+
binsFeretText: "在本區塊中,您可以配置用於粒子分布分析的直方圖區間數 - 最佳值為10-20個區間,因其能提供清晰且易於區分的峰值。",
91+
visualizationSettings: "在本部分中,您可以設定用於視覺化分割粒子輪廓和填充的參數。此外,您還可以選擇顯示費雷特直徑(Feret diameters),該直徑可直接在分割結果中顯示粒子的方向,以及顯示像素比例的選項。",
9292
modelParamsText: "很好!現在配置模型參數。",
9393
buttons: {
9494
next: '下一步',
@@ -114,8 +114,8 @@
114114
sahiSettingText: "分析大型图像(超过2000像素)且含有微小或重叠粒子时,建议启用SAHI模式(切片辅助超推理)。最佳参数包括200-400像素的切片大小和10-20%的重叠 - 这些设置在检测精度和性能之间提供平衡。减小切片尺寸可增加分析细节但会增加处理时间,而调整重叠百分比有助于改善切片连接区域的粒子检测,特别是在非均匀物体分布情况下。这些参数对于需要高分割精度的复杂图像处理尤为重要。",
115115
solutionSegmentText: "在本区域中,您可以配置分辨率:提高此参数可改善分析精度,但会导致更长的处理时间。",
116116
numberDetectionsText: "限制粒子数量:系统运行缓慢时减少,大面积稀有粒子时增加。先从1000开始,然后根据需要调整。",
117-
binsFeretText: "在本区域中,您可以配置用于粒子分布分析的直方图区间数 - 最佳值为10-20个区间,因其能提供清晰且易于区分的峰值。此处还提供显示Feret直径的选项,可直接在分割结果上显示粒子方向。",
118-
visualizationSettings: "在本节中,您可以设置可视化分段粒子轮廓和填充的参数。",
117+
binsFeretText: "在本区域中,您可以配置用于粒子分布分析的直方图区间数 - 最佳值为10-20个区间,因其能提供清晰且易于区分的峰值。",
118+
visualizationSettings: "在本部分中,您可以设置用于可视化分割粒子轮廓和填充的参数。此外,您还可以选择显示费雷特直径(Feret diameters),该直径可直接在分割结果中显示粒子的方向,以及显示像素比例的选项。",
119119
modelParamsText: "很好!现在配置模型参数。",
120120
buttons: {
121121
next: '下一步',

particleanalyzer/core/ui.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
reset_interface2,
1010
log_analytics,
1111
empty_df_ParticleCharacteristics,
12+
empty_df_ParticleCharacteristics,
1213
empty_df_ParticleStatistics,
1314
save_data_to_csv,
1415
scale_input_unit_measurement,
@@ -478,11 +479,6 @@ def create_interface(api_key):
478479
step=1,
479480
label=i18n("Интервалов на гистограмме"),
480481
)
481-
with gr.Column(scale=1):
482-
show_Feret_diametr = gr.Checkbox(
483-
label=i18n("Включить"),
484-
info=i18n("Включить отображение диаметров Ферета?"),
485-
)
486482
with gr.Group(elem_id="visualization-settings"):
487483
gr.Markdown(
488484
f"<h3 style='margin-left: 7px;'><i class='fas fa-paint-brush'></i> {i18n('Параметры визуализации')}</h3>"
@@ -515,18 +511,29 @@ def create_interface(api_key):
515511
value="rgb(0, 255, 0, 1)",
516512
label=i18n("Цвет заливки"),
517513
)
518-
with gr.Column():
514+
with gr.Column(min_width=700):
519515
fill_alpha = gr.Slider(
520516
minimum=0,
521517
maximum=1,
522518
value=0.3,
523519
step=0.01,
524520
label=i18n("Прозрачность заливки"),
525521
)
522+
with gr.Column(scale=1):
523+
show_Feret_diametr = gr.Checkbox(
524+
label=i18n("Включить"),
525+
info=i18n("Включить отображение диаметров Ферета?"),
526+
)
527+
with gr.Column(scale=1):
528+
show_Scale_bar = gr.Checkbox(
529+
value=True,
530+
label=i18n("Включить"),
531+
info=i18n("Включить отображение масштабной шкалы?"),
532+
)
526533
with gr.Tab(i18n("О программе")):
527534
gr.HTML(i18n(about_ru))
528535
with gr.Row(visible=False) as sidebar:
529-
with gr.Sidebar(width=400):
536+
with gr.Column(elem_classes="sidebar-fixed"):
530537
with gr.Row():
531538
gr.HTML(
532539
f"""<h2 style="display: flex; align-items: center; gap: 8px;">
@@ -618,6 +625,7 @@ def create_interface(api_key):
618625
sahi_mode,
619626
number_of_bins,
620627
show_Feret_diametr,
628+
show_Scale_bar,
621629
outline_color,
622630
show_fillPoly,
623631
show_polylines,

particleanalyzer/core/ui_styles.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,20 @@
6262
margin: 0 auto;
6363
}
6464
65+
/* === САЙДБАР === */
66+
.sidebar-fixed {
67+
position: fixed !important;
68+
top: 0;
69+
left: 0;
70+
width: 400px !important;
71+
height: 100vh !important;
72+
padding: 20px;
73+
box-shadow: -4px 0 15px rgba(0,0,0,0.2);
74+
background: white;
75+
overflow-y: auto;
76+
z-index: 9999;
77+
}
78+
6579
/* ==========================================================================
6680
🧩 ХЕДЕР
6781
========================================================================== */

particleanalyzer/core/utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -499,17 +499,17 @@ def img_to_numpy_array(file_path, max_size_kb=500, quality=85):
499499
return np.array(compressed_img)
500500

501501
except (IOError, OSError, ValueError) as e:
502+
gr.Info(
503+
get_translation(
504+
"Не поддерживаемый формат изображения."
505+
)
506+
)
502507
print(f"Ошибка при загрузке изображения {file_path}: {e}")
503508
return None
504509

505510

506511
def handle_file_upload(file, scale_selector):
507512
if file is None:
508-
gr.Info(
509-
get_translation(
510-
"Не поддерживаемый формат изображения."
511-
)
512-
)
513513
return gr.skip(), gr.update(visible=True), gr.update(visible=False)
514514

515515
in_image = img_to_numpy_array(file.name)

particleanalyzer/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.2.1"
1+
__version__ = "1.2.2"

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def read_file(filename):
99

1010
setup(
1111
name="ParticleAnalyzer",
12-
version="1.2.1",
12+
version="1.2.2",
1313
packages=find_packages(exclude=["tests*"]),
1414
package_data={
1515
"particleanalyzer": [
@@ -24,7 +24,7 @@ def read_file(filename):
2424
],
2525
},
2626
install_requires=[
27-
"gradio==5.35.0",
27+
"gradio==5.46.0",
2828
"gradio-rangeslider",
2929
"matplotlib",
3030
"opencv-python",

0 commit comments

Comments
 (0)