Пример #1
0
def main():
    os.environ["CUDA_VISIBLE_DEVICES"] = "0"
    # https://stackoverflow.com/a/42121886
    key = 'TF_CPP_MIN_LOG_LEVEL'
    if key not in os.environ:
        os.environ[key] = '2'

    parser = build_parser()
    options = parser.parse_args()

    if not os.path.isfile(options.network):
        parser.error("Network %s does not exist. (Did you forget to "
                     "download it?)" % options.network)

    if [options.checkpoint_iterations,
            options.checkpoint_output].count(None) == 1:
        parser.error("use either both of checkpoint_output and "
                     "checkpoint_iterations or neither")

    if options.checkpoint_output is not None:
        if re.match(r'^.*(\{.*\}|%.*).*$', options.checkpoint_output) is None:
            parser.error("To save intermediate images, the checkpoint_output "
                         "parameter must contain placeholders (e.g. "
                         "`foo_{}.jpg` or `foo_%d.jpg`")

    content_image = imread(options.content)
    style_images = [imread(style) for style in options.styles]

    width = options.width
    if width is not None:
        new_shape = (int(
            math.floor(
                float(content_image.shape[0]) / content_image.shape[1] *
                width)), width)
        content_image = misc.imresize(content_image, new_shape)
    target_shape = content_image.shape
    for i in range(len(style_images)):
        style_scale = STYLE_SCALE
        if options.style_scales is not None:
            style_scale = options.style_scales[i]
        style_images[i] = misc.imresize(
            style_images[i],
            style_scale * target_shape[1] / style_images[i].shape[1])

    style_blend_weights = options.style_blend_weights
    if style_blend_weights is None:
        # default is equal weights
        style_blend_weights = [1.0 / len(style_images) for _ in style_images]
    else:
        total_blend_weight = sum(style_blend_weights)
        style_blend_weights = [
            weight / total_blend_weight for weight in style_blend_weights
        ]

    initial = options.initial
    if initial is not None:
        initial = misc.imresize(imread(initial), content_image.shape[:2])
        # Initial guess is specified, but not noiseblend - no noise should be blended
        if options.initial_noiseblend is None:
            options.initial_noiseblend = 0.0
    else:
        # Neither inital, nor noiseblend is provided, falling back to random
        # generated initial guess
        if options.initial_noiseblend is None:
            options.initial_noiseblend = 1.0
        if options.initial_noiseblend < 1.0:
            initial = content_image

    # try saving a dummy image to the output path to make sure that it's writable
    if os.path.isfile(options.output) and not options.overwrite:
        raise IOError("%s already exists, will not replace it without "
                      "the '--overwrite' flag" % options.output)
    try:
        imsave(options.output, np.zeros((500, 500, 3)))
    except:
        raise IOError('%s is not writable or does not have a valid file '
                      'extension for an image file' % options.output)

    loss_arrs = None
    for iteration, image, loss_vals in stylize(
            network=options.network,
            initial=initial,
            initial_noiseblend=options.initial_noiseblend,
            content=content_image,
            styles=style_images,
            preserve_colors=options.preserve_colors,
            iterations=options.iterations,
            content_weight=options.content_weight,
            content_weight_blend=options.content_weight_blend,
            style_weight=options.style_weight,
            style_layer_weight_exp=options.style_layer_weight_exp,
            style_blend_weights=style_blend_weights,
            tv_weight=options.tv_weight,
            learning_rate=options.learning_rate,
            beta1=options.beta1,
            beta2=options.beta2,
            epsilon=options.epsilon,
            pooling=options.pooling,
            print_iterations=options.print_iterations,
            checkpoint_iterations=options.checkpoint_iterations,
    ):
        print(image)
        if (image is not None) and (options.checkpoint_output is not None):
            imsave(fmt_imsave(options.checkpoint_output, iteration), image)
        if (loss_vals is not None) \
                and (options.progress_plot or options.progress_write):
            if loss_arrs is None:
                itr = []
                loss_arrs = OrderedDict((key, []) for key in loss_vals.keys())
            for key, val in loss_vals.items():
                loss_arrs[key].append(val)
            itr.append(iteration)

    imsave(options.output, image)

    if options.progress_write:
        fn = "{}/progress.txt".format(os.path.dirname(options.output))
        tmp = np.empty((len(itr), len(loss_arrs) + 1), dtype=float)
        tmp[:, 0] = np.array(itr)
        for ii, val in enumerate(loss_arrs.values()):
            tmp[:, ii + 1] = np.array(val)
        np.savetxt(fn, tmp, header=' '.join(['itr'] + list(loss_arrs.keys())))

    if options.progress_plot:

        matplotlib.use('Agg')

        fig, ax = plt.subplots()
        for key, val in loss_arrs.items():
            ax.semilogy(itr, val, label=key)
        ax.legend()
        ax.set_xlabel("iterations")
        ax.set_ylabel("loss")
        fig.savefig("{}/progress.png".format(os.path.dirname(options.output)))
import streamlit as st
from PIL import Image
import os

import style

st.title('Pytorch style transfer')

img = st.sidebar.selectbox('Select Image', ('amber.jpg', 'dog.jpg'))

style_name = st.sidebar.selectbox(
    'Select Style', ('candy', 'mosaic', 'rain_princess', 'udnie'))

model = 'saved_models/' + style_name + '.pth'
input_image = 'images/content-images/' + img
print(input_image)
output_image = 'images/output-images/' + style_name + '-' + img

st.write('### Source image:')
image = Image.open(input_image)
st.image(image, width=400)

clicked = st.button('stylize')
if clicked:
    model = style.load_model(model)
    style.stylize(model, input_image, output_image)

    st.write('### output image:')
    image = Image.open(output_image)
    st.image(image, width=400)
Пример #3
0
def mainapp():

    temp = """
    <link href='https://fonts.googleapis.com/css?family=Bigshot One' rel='stylesheet'>
    <div style="background-color:#464e5f;padding:30px,margin:10px;border-radius:25px;">
    <h3 style="color:white;text-align:center;padding:30px;font-family: 'Bigshot One';font-size:40px;">Computer Based Artistic Works</h3>
    </div>
    """
    st.markdown(temp, unsafe_allow_html=True)
    st.sidebar.markdown(
        """<link href='https://fonts.googleapis.com/css?family=Bayon' rel='stylesheet'><br>
    <div>
        <p style="color:black;font-family: 'Bayon';font-size:20px;">Select Content Image</p>
    </div>""",
        unsafe_allow_html=True)
    img = st.sidebar.selectbox('', ('amber.jpg', 'puppies.jpg', 'donuts.jpg',
                                    'drinks.jpg', 'wall-of-china.jpg'))

    st.sidebar.markdown(
        """<link href='https://fonts.googleapis.com/css?family=Bayon' rel='stylesheet'>
    <div>
        <p style="color:black;font-family: 'Bayon';font-size:20px;">Select Style</p>
    </div>""",
        unsafe_allow_html=True)

    style_name = st.sidebar.selectbox(
        '', ('candy', 'mosaic', 'rain-princess', 'udnie'))
    model = "saved_models/" + style_name + ".pth"
    style_image = "images/style-images/" + style_name + ".jpg"
    input_image = "images/content-images/" + img
    col1, col2 = st.columns(2)
    col1.markdown(
        """<link href='https://fonts.googleapis.com/css?family=Bree Serif' rel='stylesheet'>
        <div>
    <h3 style="color:black;font-family: 'Bree Serif';font-size:30px;">Source Image:</h3>
    </div>""",
        unsafe_allow_html=True)
    image = Image.open(input_image)
    col1.image(image, width=330)

    col2.markdown(
        """<link href='https://fonts.googleapis.com/css?family=Bree Serif' rel='stylesheet'>
        <div>
    <h3 style="color:black;font-family: 'Bree Serif';font-size:30px;">Style Image:</h3>
    </div>""",
        unsafe_allow_html=True)
    image2 = Image.open(style_image)
    col2.image(image2, width=330)

    output_image = "images/output-images/" + style_name + "-" + img

    session_state = SessionState.get(checkboxed=False)

    def local_css(file_name):
        with open(file_name) as f:
            st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)

    local_css("style.css")

    clicked = st.button("Stylize")

    def get_image_download_link(img):

        buffered = BytesIO()
        img.save(buffered, format="JPEG")
        img_str = base64.b64encode(buffered.getvalue()).decode()
        href = f'<a href="data:file/jpg;base64,{img_str}" download="Image.jpg">Download result</a>'
        return href

    if clicked or session_state.checkboxed:
        session_state.checkboxed = True
        model = style.load_model(model)
        style.stylize(model, input_image, output_image)

        st.markdown(
            """<link href='https://fonts.googleapis.com/css?family=Bree Serif' rel='stylesheet'>
        <div>
    <h3 style="color:black;font-family: 'Bree Serif';font-size:30px;">Output Image:</h3>
    </div>""",
            unsafe_allow_html=True)
        image = Image.open(output_image)
        st.image(image, width=400)
        st.info("Only Registered Users can Downoad the output Image!!")
        t1 = """
        <link href='https://fonts.googleapis.com/css?family=Bigshot One' rel='stylesheet'>
        <div>
    <h3 style="color:black;margin-bottom:-30px;font-family: 'Bigshot One';font-size:30px;">Have You Registered?<span style='font-size:30px;'>&#129300;</span></h3> </div><br><br>
        """
        st.markdown(t1, unsafe_allow_html=True)
        radio = st.radio("", ('Yes', 'No'))
        if (radio == 'Yes'):
            st.markdown(
                """<link href='https://fonts.googleapis.com/css?family=Bree Serif' rel='stylesheet'>
        <div>
            <h3 style="color:black;font-family: 'Bree Serif';font-size:20px;margin-bottom:-20px;">Enter Username..</h3>
        </div>""",
                unsafe_allow_html=True)
            user = st.text_input("", "")
            st.markdown(
                """<link href='https://fonts.googleapis.com/css?family=Bree Serif' rel='stylesheet'>
            <div>
                <h3 style="color:black;font-family: 'Bree Serif';font-size:20px;margin-bottom:-20px;">Enter Password..</h3>
            </div>""",
                unsafe_allow_html=True)
            passw = st.text_input("", "", type="password")
            if st.button("Go"):
                result = login_user(user, passw)
                if result:
                    st.success("Logged in as {}".format(user))
                    image1 = Image.open(output_image)
                    st.markdown(get_image_download_link(image1),
                                unsafe_allow_html=True)
                else:
                    st.warning("Incorrect Username/Password")

        if (radio == 'No'):
            st.warning(
                "Please Register Yourself Using the Signup Option in the Navigation bar"
            )
Пример #4
0
# print(style_image_name)


image=Image.open(input_image_name)
style_image=Image.open(style_image_name)

col1, col2 = st.beta_columns(2)

col1.header("Source Image:")
col1.image(image, use_column_width=True)

col2.header("Style Image:")
col2.image(style_image, use_column_width=True)



clicked=st.button("Stylize")




if clicked:
    model=style.load_model(model_name)
    style.stylize(model,input_image_name,output_image_name)

    st.write("### Output Image:")
    image=Image.open(output_image_name)
    st.image(image,width=400)


Пример #5
0
input_image_path = ''
if input_image is not None:
    input_image_path = 'neural_style/images/content-images/' + input_image.name

st.write('### Source Image:')
if input_image is not None:
    with open(
            os.path.join("neural_style/images/content-images/",
                         input_image.name), "wb") as f:
        f.write(input_image.getbuffer())
    img = Image.open(input_image)
    st.image(img, width=250)

if input_image:
    st.write(input_image.name)

style_name = st.selectbox('Select Style',
                          ('candy', 'mosaic', 'rain_princess', 'udnie'))

model = 'neural_style/saved_models/' + style_name + '.pth'
if input_image is not None:
    output_image = 'neural_style/images/output-images/' + style_name + '-' + input_image.name
clicked = st.button('Stylize')

if clicked:
    model = style.load_model(model)
    style.stylize(model, input_image_path, output_image)

    st.write('### Stylized Image:')
    image = Image.open(output_image)
    st.image(image, width=400)