Home > Software design >  How to add a box inside the image using python
How to add a box inside the image using python

Time:08-11

I have a code which convert the image into color sketch in that i have added a text(water mark) due to the dark background the text is not properly visible so i need a box with white background so that text would be clearly visible

To display text in bottom right i have did some calculation using width and height

Thanks in Advance

import streamlit as st

import numpy as np

from PIL import Image,ImageDraw,ImageFont

import cv2




def color_quantization(img, k):

# Transform the image

  data = np.float32(img).reshape((-1, 3))



# Determine criteria

  criteria = (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)



# Implementing K-Means

  ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

  center = np.uint8(center)

  result = center[label.flatten()]

  result = result.reshape(img.shape)

  return result



file_image = st.sidebar.file_uploader("Upload your Photos", type=['jpeg','jpg','png'])

    

if file_image is None:

    st.write("You haven't uploaded any image file")

    

else:

    image = Image.open(file_image)

    st.image(image)

    width, height = image.size 

    final1 =ImageDraw.Draw(image)

    text = "my sketch"

    textwidth, textheight = final1.textsize(text)

    margin = 10

    x = width - textwidth - margin

    y = height - textheight - margin

    final1.text((x,y), text,fill ="Black")

    final_sketch = color_quantization(np.array(image),9)

    st.image(final_sketch, use_column_width=True)

CodePudding user response:

Just use ImageDraw.rectangle() to draw a white rectangle before adding the text:

final1.rectangle((x,y,width,height), fill="white")

I think some folk call it an "underbox".

  • Related