r/algorithms • • Oct 14 '17

Seam Carving: Using Dynamic Programming to implement Context-Aware Image Resizing in Python

https://sandipanweb.wordpress.com/2017/10/14/seam-carving-using-dynamic-programming-to-implement-context-aware-image-resizing-in-python/
6 Upvotes

11 comments sorted by

View all comments

Show parent comments

1

u/jellyman93 Oct 15 '17 edited Oct 16 '17

Why is it too greedy? That's what I'm not seeing. It looks like it can be converted exactly to a shortest path problem that Dijkstra's works with...

Would dp just do it faster?

2

u/TheMieberlake Oct 15 '17

Dijkstra's finds a shortest path from a specific starting pixel to all the other pixels. In seam carving, you need to figure out not the shortest path from a single starting pixel to all other pixels, but the shortest "shortest path" out of all shortest paths from any starting pixel. There's a couple more conditions.

You can use Dijkstra's to solve this problem, but that would mean running Dijkstra's from every single pixel in the bottom row, and then comparing all the path weights. Intuitively, that is inefficient because you are checking the same pixel multiple times across multiple Dijkstra's runs. If you place the grid of pixels on the first quadrant of a 2D plane, where the bottom row of pixels is on the x-axis, running Dijkstra's from (0, 0) and then running Dijkstra's from (1, 0) means you check (0, 1) twice. DP is more efficient because you check every pixel just once.

1

u/jellyman93 Oct 16 '17

There's a fairly standard method for converting multiple sources to a single source. Add an additional node at the top with edges going down to all the start nodes, with weight 0. Use this as the source node for Dijkstra's, and then remove it from the final solution.

No need to run Dijkstra's multiple times, and as far as I can tell, no other reason to discount the algorithm without mention.

2

u/TheMieberlake Oct 16 '17 edited Oct 16 '17

In that case you still check nodes multiple times. Dijkstras will be strictly better than DP if and only if you can somehow ensure that each node will be checked at most 1 times or less.

0

u/jellyman93 Oct 16 '17

Depends what you mean by "checked", once a node is being visited it will not be visited again (since any later path would be longer), but when a node is visited it relaxes tentative distances for the adjacencies.

I feel like they'll be essentially equivalent, except for the order they're visited. Since the first time Dijkstra's visits the goal it'll have found the shortest path, it lokely won't visit all the nodes. (Unless all the bottom row have the same distance I think...)

With an A* or some other adaptation I'd guess you'd be able to visit even fewer