if y1 < nx and x1 < ny and x2 > 0 and y2 > 0:
            imhead = im[y1:y2, x1:x2, :]
            #imsave('whaletail_' + imageid + '.png', imhead)


        def differ(im, ch1, ch2):
            diffim = im[:, :, 0] + im[:, :, 1] + im[:, :, 2]
            normdiff =  diffim.max() / diffim
            smoothdiff = gaussian_filter(normdiff, 20)
            return smoothdiff



        diffim = 2 * im[:, :, 0] - im[:, :, 1] - im[:, :, 2]
        #plt.clf()
        imcolor, imlumin, colorthresh = colorlumin(im)
        if colorthresh == 0:
            continue
        plt.clf()
        plt.imshow(imcolor)
        plt.contour(whale_model)
        plt.colorbar()

        plt.plot([xhead1], [yhead1], 'o')
        plt.plot([xhead2], [yhead2], 'o')

        plt.savefig('whalemodel_' + imagenum + '.png')
        #imluminmask = imlumin < 0.8
        #imdiff = imcolor - whale_model
        #print(imdiff[imluminmask].sum())
        #plt.imshow(imcolor, origin='lower')
        #toohigh = diffim > 5
        #diffim[toohigh] = 5.
        #toolow = diffim < 1
        #diffim[toolow] = 0.
        #print(diffim.mean())

        from scipy.misc import imresize
        ny, nx = diffim.shape
        #print(nx, ny)
        smallim = np.zeros((ny/rebin, nx/rebin, 3))
        for i in range(3):
            smallim[:, :, i] = imresize(im3[:, :, i], 1/rebin)

        # get the color and luminesence of the binned RGB image
        #colorthresh = -60.0
        imcolor, imlumin, colorthresh = whaleutil.colorlumin(smallim)

        imluminmask = imlumin < 0.9
        # mask regions with a strong wave signature
        #waveindex = imlumin > 300
        #imcolor[waveindex] = 0

        # first guess at whale region
        #hicol = imcolor >= 5
        #imcolor[hicol] = 5.
        #toolow = imcolor < 1
        #imcolor[toolow] = 0.
        #print(smallim.mean())

        ny, nx = imcolor.shape
        #print(nx, ny)