I had some issues with the code from Jonathan in the case a post already has a thumbnail. (E.g: after modifying the contents of the custom image field)
The solution that works for me is to put the line:
delete_post_thumbnail( $post_id);
before the line
add_post_meta($post_id, '_thumbnail_id', $value);