What is wrong my flood fill algorithm?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By exuin
func separate(image: Image) -> void:
	var images := []
	image.lock()
	for y in image.data.height:
		for x in image.data.width:
			if image.get_pixel(x, y).a != 0.0:
				var start_y: int = y
				var end_y: int = y + 1
				var start_x: int = x
				var end_x: int = x + 1
				var checked_pixels := []
				var pixels := [Vector2(x, y)]
				while not pixels.empty():
					var pixel: Vector2 = pixels.pop_back()
					if image.get_pixelv(pixel).a != 0.0:
						var neighbors := []
						if not x == image.data.width - 1:
							neighbors.append(Vector2(x + 1, y))
						if not x == 0:
							neighbors.append(Vector2(x - 1, y))
						if not y == image.data.height - 1:
							neighbors.append(Vector2(x, y + 1))
						if not y == 0:
							neighbors.append(Vector2(x, y - 1))
						for new_pixel in neighbors:
							if not new_pixel in checked_pixels:
								pixels.append(new_pixel)
					else:
						if start_y > pixel.y + 1:
							start_y = pixel.y
						if end_y < pixel.y:
							end_y = pixel.y
						if start_x > pixel.x + 1:
							start_x = pixel.x
						if end_x < pixel.x:
							end_x = pixel.x
					checked_pixels.append(pixel)
				var rect := Rect2(start_x, start_y, end_x - start_x, end_y - start_y)
				images.append(image.get_rect(rect))
				image.fill_rect(rect, Color.transparent)
				image.lock()
	image.unlock()
	print(images.size())

The error is “All memory pool allocations are in use.”

image.lock()

Wakatta | 2022-11-30 23:56

Read this again Image — Godot Engine (stable) documentation in English

Returns the color of the pixel at src if the image is locked. If the image is unlocked, it always returns a Color with the value (0, 0, 0, 1.0). This is the same as get_pixel, but with a Vector2 argument instead of two integer arguments.

I need to lock the image to get teh color of the pixel.

exuin | 2022-12-01 00:33

why do you call it twice?

Wakatta | 2022-12-01 15:41

:bust_in_silhouette: Reply From: exuin

I think the issue here was that there was too many loops.

Always have and always will hate while loops and pretty sure the above does not need it

Wakatta | 2022-12-10 14:12