I'm trying to draw text on my image but it's not showing up - python-2.7

I'm making a function that adds a border on a picture than applies text at a certain position but the text is not showing. I have the ttf font in my worker directory.
from PIL import Image, ImageDraw, ImageOps, ImageFont
def framemaker1(original_image,percentwth,color,text,textcolor,textsize):
img=Image.open(original_image)
width,height=img.size
thefont=ImageFont.truetype('BROADW.ttf',textsize)
framewth=int(width*percentwth)
framedimg=ImageOps.expand(img,border=framewth,fill=color)
draw=ImageDraw.Draw(framedimg)
draw.text=((framewth,height+framewth+0.25*framewth),text,thefont)
framedimg.save('framed'+original_image)
framedimg.show()
print img.size
I wanted to have the text at the bottom right corner but no text appears.

Related

how can return cv2.imshow() image to browser in django

In ac I got the images with their score of similarity in list format. I want to display all images in browser using django. How can I display each image in browser?
ac=obj.perform(newdoc.docfile.path)
for (score,resultID) in ac:
result = cv2.imread(path1 + "/" + resultID)
# cv2.imshow("Result", result)
return HttpResponse(cv2.imshow("Result", result))
From cv2.show("Result",result) a popup window is opened and shows the image but when I go through HttpResponse passing the image to the browser it gives the result None. How can I solve the issue?
You cannot do this by one view. I would suggest to have 2 views. first displays single image using StreamResponse. And second view will have a template where it goes trough every image and has <img> tag which src shows to your first view.
Also you cannot use cv2.imshow(), I'm not cv2 expert but as far as I know that function is for displaying your image in window. In your case you need to read the binary data from your cv2 object and pass it to StreamResoponse object as django response.
Other possible way is to have a template where you create img tag for each your case and put binary data to it as follows:
<img src="data:image/png;base64,{{ base64_data_from_cv2_object}}"/>

Show preview of image in form

I want to achieve the following in a django form, for a models.ImageField:
do not show the standard <input type="file"> button ("choose file" button)
show a preview of the current image, for already populated models
for empty (new) models, show a custom button
clicking on the image preview or the custom button will open a file dialog to select the image from the user's file system
selecting a new image replaces the custom button or the old image preview with the preview of the new image
This seems to me like a normal workflow to select images in a form, but I do not seem to find any fully working solution. All I can find involves hacking around several parts:
styling the label and hiding the standard "choose file" button: https://www.youtube.com/watch?v=4p2gTDZKS9Y
use a widget instead of the standard for forms.FileField.
I have tried to use:
class ImagePreviewWidget(Widget):
def render(self, name, value, attrs=None):
return mark_safe('<img src="/media/%s" width="100px"/>' % escape(value))
For the widget, and I am using this in the form like this:
class DesignCampaignForm(ModelForm):
brand_logo = FileField(widget=ImagePreviewWidget)
This is properly showing the preview of the existing image, but I am unable to click on it to select another file, and even if I was that would not update the preview.
Is there an already available solution for this simple use case?
I haven't been able to find a complete solution, so I have done the following:
use a widget to render a modified ClearableFileInput, rendering an image and an <input> element
style the <input> in the element with CSS, to hide it
make sure that clicking in the image triggers the hidden <input> element, wrapping the <img> in a <label> and using the for attribute
add some javascript to replace the image preview whenever the selection in the <input> element changes
whenever the selection is cleared, show the original preview
A gist can be found here.
In my final solution (not yet in the gist), I have added a button for when the image is not yet selected.
edit: Gist only works for Django before version 1.11.x.
class ClearableFileInput has since been gutted and changed

django-image-cropping how to via view serve cropped image

I am using django-image-cropping in my project.
doc says:
The original images are kept intact and only get cropped when they are displayed. Large images are presented in a
small format, so even very big images can easily be cropped.
In my model i have fields:
logo = ImageCropField(upload_to=get_image_path, null=True, blank=True)
cropping_logo = ImageRatioField('logo', '186x186', size_warning=True)
User can adjust cropping of the photo in admin panel. Like in picture below.
Changes are kept ONLY in cropping_logo field as numeric values indicating the cropping vertices, e.g: 91,0,239,148
I would like to serve via some url dynamically cropped image based on cropping vertices, but don't know how.
UPDATE: Basing on hint of ubadub to use PIL I figured out following solution using such view.
def thumbnail(request, image_file):
image_file = '/'.join(('img', image_file))
f = MyModel.objects.get(logo=image_file)
img = Image.open(''.join((os.getcwd(), f.logo.url)))
box = tuple([int(i) for i in f.cropping_logo.split(',')])
img = img.crop(box)
response = HttpResponse(mimetype="image/png")
img.save(response, "jpeg")
return response
needed imports are:
import os
from PIL import Image
from django.http import HttpResponse
your url pattern may look as follows:
url(r'^thumbnail/(?P<image_file>.+)$', 'yourapp.views.thumbnail'),
Well, one option is to serve some view at some url that returns the image cropped with css:
Example css:
img
{
position:absolute;
clip:rect(0px,60px,200px,0px);
}
where the clip:rect has the dimensions defined in your model.
The css could be inline (bad practice, but whatever) or in a dynamically served css file (also probably not the best idea to serve a css file dynamically, but necessary in this case).
However this would still serve a html page. So another option if you want to serve a page of mime-type image, then do this, but you'll need PIL (Python Image Library):
response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")
return response
where img is the original image cropped to the specified dimensions.
And of course replace png with whatever file format your image is in.

python:window with no title bar, and change window default color(grey) to black

I wrote a code to pop up a window on my screen and to print a data on the window.Here according to my requirement i want the entire screen to be BLACK in color. SO that i can print some text on that black window. The window title bar tkinter should be removed and the entire window screen should be in black.
Try self.configure(background='black') or self['bg'] = 'black'. Most Tkinter widgets can be configured with similar properties.
Just do:
from tkinter import *
root = Tk()
root.title('')
root.config(background='black')
root.mainloop()
And that should work!

QT - multi-select

I would like to create a search-type text field in QT that can contain both standard text as well as what I would call "tags"... basically additional search terms that are individually highlighted and separated. I envision this looking like the multi-select in "Chosen" (Javascript library). http://harvesthq.github.com/chosen/
I have been unable to find anything similar through searching. It also seems that the standard QT text box types are not designed to have "sub-widgets".
It appears that QTextEdit supports HTML... that might be a possiblity... but the docs are not very clear to me as what is supported in terms of CSS (which I think would be required to get the desired formatting). http://doc.qt.io/qt-5/qtextedit.html#html-prop
Its funny... I got to the bottom of this submission page and realized I have to tag this (this is my first SO question)... This tag-adder box is almost exactly what I want!
There is no ready-to-use soultion that I know.
If I were to try implementing it, I would definitely use widget with layout, in which there are two types of child widgets: LineEdits (borderless to look like actual part of bigger widget) and buttons - code managing line edit changes would simply add new buttons before or after and if necesary splited linedit into tw with button between. This way is not interfering with qt programers intentions on how to use widgets and how to make them all fit together in one style.
If you want you can use custom widgets instead of buttons to provide remove icon.
As I wrote in my comment - if i have a bit more time I will try to make something like that myself.
Here is a very simple implementation of putting buttons in a QLineEdit as a user types, written in Python:
from PySide.QtCore import *
from PySide.QtGui import *
class Entry(QLineEdit):
def __init__(self):
QLineEdit.__init__(self)
self.buttons = []
self.backupText = ''
self.textEdited.connect(self.on_change)
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.layout.addStretch()
marginz = QLabel(' ')
marginz.show()
margin = marginz.width()
marginz.hide()
self.layout.setContentsMargins(margin, margin, margin, margin)
def on_change(self):
if self.text()[-1] == ' ' and not self.text().endswith(' '):
if len(self.text()) > len(self.backupText):
self.setText(self.text() + ' ')
self.buttons.append(QPushButton(self.text().split()[-1]))
self.layout.insertWidget(self.layout.count()-1, self.buttons[-1])
else:
self.setText(self.text()[0:-1])
self.buttons[-1].hide()
del self.buttons[-1]
self.backupText = self.text()
app = QApplication([])
window = QMainWindow()
window.setStyleSheet(
'QPushButton {border: 1px solid gray; background: lightgray; color: black;}')
entry = Entry()
window.setCentralWidget(entry)
window.show()
app.exec_()
It creates a QHBoxLayout and adds a button to it for each word you type, and takes the button away when you get rid of the word.
If you want to put a close button inside of each of the sub-widgets, you can make a custom widget for that too.
EDIT
As j_kubik's comment stated, systems with wide-margin buttons would cause the tag buttons to overlap the text a user is currently typing. I have modified the code to enforce the margins of the buttons inserted (with stylesheets), added an extra space for each space the user types, and set the QHBoxLayout's contentsMargins to be the same width as a space (""). Now the buttons will not overlap the text inserted.