Get caption from unattached images in gallery?

<?php $loop = new WP_Query( array( 'post_type' => 'gallery', 
        'posts_per_page' => 100 ) 
            ); 
        while ( $loop->have_posts() ) : $loop->the_post();

        if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :

            $img_ids = explode( ',', $gallery['ids'] );
            /* Loop through all the image and output them one by one */
            foreach( $gallery['src'] as $key => $src ) : ?>

                <img src="https://wordpress.stackexchange.com/questions/307061/<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />
                <?php
                    $image_post = get_post( $img_ids[ $key ] ); ?>
                    <p class="wp-caption-text"><?php echo $image_post->post_excerpt; ?></p>

            <?php endforeach;
        endif;

 endwhile; wp_reset_postdata(); ?>

error code: 523