Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Cropping an image by color in Python

I would like to crop an image and for that, I am using the pyvips package (if you have another package which allows me to do the work faster than my method, share it) in Python. My code does not work as intended:

Below all my code:

import sys
import pyvips
from skimage import io
from matplotlib import pyplot as plt
import numpy as np

def show_image(image, title='Image', cmap_type='gray'):
    plt.imshow(image, cmap=cmap_type)
    plt.title(title)
    plt.axis('off')
    plt.show()
def outline(file_name, new_file_name):
    file = os.path.join(file_name)
    im = pyvips.Image.new_from_file(file)

    # find the value of the pixel at (0, 0) ... we will search for all pixels 
    # significantly different from this
    background = im(0, 0)


    # we need to smooth the image, subtract the background from every pixel, take 
    # the absolute value of the difference, then threshold
    mask = (im.median(3) - background).abs() > 10

    # sum mask rows and columns, then search for the first non-zero sum in each
    # direction
    columns, rows = mask.project()

    # .profile() returns a pair (v-profile, h-profile) 
    left = columns.profile()[1].min()
    right = columns.width - columns.fliphor().profile()[1].min()
    top = rows.profile()[0].min()
    bottom = rows.height - rows.flipver().profile()[0].min()

    # and now crop the original image

    im = im.crop(left, top, right - left, bottom - top)

    im.write_to_file(new_file_name)
    return show_image(io.imread(os.path.join(new_file_name)))

For an image like that:

simple_image

my code works, but it does not work for the image I want to crop: image to crop

Here I just want to retrieve what's in the red rectangle.

And to do that I just change one thing in the outline function, I change the background value:

limit = [157.0, 101.0, 112.0]
background = limit

The limit here is the RVB code of the red color in the image I want to crop. And I don't know why my function does not return what I want, the red rectangle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...