Skip to content

Commit e3731d5

Browse files
authored
Fixes (#31)
* feat: enhance logging and add dataset generation for pith detection * chore: bump version to 0.2.1
1 parent 7499d2a commit e3731d5

File tree

4 files changed

+113
-16
lines changed

4 files changed

+113
-16
lines changed

tree-disk-segmentation/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "tree-disk-segmentation"
3-
version = "0.2.0"
3+
version = "0.2.1"
44
description = "A package for tree disk segmentation in images"
55
authors = ["Tony <tonymeissner70@gmail.com>"]
66
license = "MIT"

tree-disk-segmentation/src/treedisksegmentation/config.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,11 @@ def _validate_and_set_paths(self):
7070
if self.model_path:
7171
model_path = Path(self.model_path)
7272
if not model_path.exists():
73-
raise ValueError(f"Model file does not exist: {model_path}")
73+
logger.warning(f"Model file does not exist: {model_path}")
74+
# raise ValueError(f"Model file does not exist: {model_path}")
7475
if not model_path.is_file():
75-
raise ValueError(f"Model path is not a file: {model_path}")
76+
logger.warning(f"Model path is not a file: {model_path}")
77+
# raise ValueError(f"Model path is not a file: {model_path}")
7678
self.model_path = model_path.resolve()
7779

7880
def _log_change(self, param: str, old_value: Any, new_value: Any):
@@ -157,13 +159,5 @@ def configure(**kwargs):
157159
158160
Args:
159161
**kwargs: Configuration parameters to update.
160-
161-
Example:
162-
>>> configure(
163-
... input_image="sample.jpg",
164-
... method="apd_dl",
165-
... model_path="weights.pth",
166-
... st_w=7
167-
... )
168162
"""
169163
config.update(**kwargs)

tree-disk-segmentation/src/treedisksegmentation/models/yolo.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,13 @@ def run_yolo_detection(img_in: np.ndarray) -> Optional[List[np.ndarray]]:
3737
save_txt=config.save_results,
3838
)
3939

40-
results_len = len(results)
40+
logger.info(f"YOLO detection complete.")
4141

42-
logger.info(f"YOLO detection complete, {results_len} log(s) found.")
43-
44-
if results_len == 0:
42+
if results or len(results) == 0:
4543
logger.error("No results found in YOLO detection.")
4644
return None
4745

48-
# were just using the first result, so the first log found
46+
# were just using the first result
4947
first_result = results[0]
5048

5149
# xy = first_result.masks.xy # mask in polygon format

tree-disk-segmentation/training/yolo.ipynb

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,111 @@
174174
"\n",
175175
" cv2.imwrite('segmented_objects.jpg', background)"
176176
]
177+
},
178+
{
179+
"cell_type": "markdown",
180+
"metadata": {},
181+
"source": [
182+
"# generate dataset for pith detection"
183+
]
184+
},
185+
{
186+
"cell_type": "code",
187+
"execution_count": null,
188+
"metadata": {},
189+
"outputs": [],
190+
"source": [
191+
"dataset_path = \"/Users/tonymeissner/Downloads/bilder\"\n",
192+
"output_folder = \"output\"\n",
193+
"model_path = \"/Users/tonymeissner/source/tree-disk-analyzer/tree-disk-segmentation/models/yolo11s-seg-tree.pt\""
194+
]
195+
},
196+
{
197+
"cell_type": "code",
198+
"execution_count": null,
199+
"metadata": {},
200+
"outputs": [],
201+
"source": [
202+
"# Create output directory if it doesn't exist\n",
203+
"os.makedirs(output_folder, exist_ok=True)\n",
204+
"\n",
205+
"# Function to check if file is a valid image\n",
206+
"def is_valid_image(filepath):\n",
207+
" # Skip macOS resource fork files and hidden files\n",
208+
" if os.path.basename(filepath).startswith('._') or os.path.basename(filepath).startswith('.'):\n",
209+
" return False\n",
210+
" \n",
211+
" # Check file extension\n",
212+
" if not filepath.lower().endswith('.jpg'):\n",
213+
" return False\n",
214+
" \n",
215+
" # Verify file exists\n",
216+
" if not os.path.exists(filepath):\n",
217+
" return False\n",
218+
" \n",
219+
" return True\n",
220+
"\n",
221+
"# Find all valid image files\n",
222+
"image_paths = []\n",
223+
"for file in os.listdir(dataset_path):\n",
224+
" full_path = os.path.join(dataset_path, file)\n",
225+
" if os.path.isfile(full_path) and is_valid_image(full_path):\n",
226+
" image_paths.append(full_path)\n",
227+
"\n",
228+
"print(f\"Found {len(image_paths)} valid images\")"
229+
]
230+
},
231+
{
232+
"cell_type": "code",
233+
"execution_count": null,
234+
"metadata": {},
235+
"outputs": [],
236+
"source": [
237+
"import treedisksegmentation\n",
238+
"import logging\n",
239+
"import gc\n",
240+
"\n",
241+
"def process_image(image_path, output_folder, model_path):\n",
242+
" \"\"\"Process a single image with YOLO segmentation.\"\"\"\n",
243+
" try:\n",
244+
" output_path = os.path.join(output_folder, os.path.basename(image_path))\n",
245+
"\n",
246+
" if os.path.exists(output_path):\n",
247+
" print(f\"Skipping existing output: {image_path}\")\n",
248+
" return True\n",
249+
"\n",
250+
" treedisksegmentation.configure(\n",
251+
" model_path=model_path,\n",
252+
" input_image=image_path,\n",
253+
" )\n",
254+
"\n",
255+
" result_image, masks = treedisksegmentation.run()\n",
256+
"\n",
257+
" if masks is None:\n",
258+
" print(f\"No masks detected for image: {image_path}\")\n",
259+
" return False\n",
260+
"\n",
261+
" result_image = cv2.cvtColor(result_image, cv2.COLOR_RGB2BGR)\n",
262+
" cv2.imwrite(output_path, result_image)\n",
263+
" print(f\"Successfully processed: {image_path}\")\n",
264+
" return True\n",
265+
"\n",
266+
" except Exception as e:\n",
267+
" logging.error(f\"Error processing {image_path}: {str(e)}\", exc_info=True)\n",
268+
" return False"
269+
]
270+
},
271+
{
272+
"cell_type": "code",
273+
"execution_count": null,
274+
"metadata": {},
275+
"outputs": [],
276+
"source": [
277+
"for image_path in image_paths:\n",
278+
" process_image(image_path, output_folder, model_path)\n",
279+
" print(f\"{image_paths.index(image_path)} / {len(image_paths)} images processed\")\n",
280+
" gc.collect()"
281+
]
177282
}
178283
],
179284
"metadata": {

0 commit comments

Comments
 (0)