pyglet label not showing on screen on draw() with OpenAI gym render - pyglet

I'm using a wrapper of OpenAI gym to create a graphical representation of a problem. For that, I'm drawing a circle with the given wrapper and then try to add some text.
My issue is, that only the circle shows, but the text label does not appear. Any suggestions on how I can make the text visible would be highly appreciated. Below a minimal example, that show the problem:
import pyglet
from gym.envs.classic_control import rendering
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.render(return_rgb_array=False)
input()

What worked for me is to manually implement the render function and insert the label after the tranform.disable()
## Content of the render function
glClearColor(1, 1, 1, 1)
self.viewer.window.clear()
self.viewer.window.switch_to()
self.viewer.window.dispatch_events()
self.viewer.transform.enable()
for geom in self.viewer.geoms:
geom.render()
for geom in self.viewer.onetime_geoms:
geom.render()
self.viewer.transform.disable()
# Text
label = pyglet.text.Label(
"Hello, world",
font_name="Times New Roman",
font_size=36,
x=100,
y=100,
anchor_x="center",
anchor_y="center",
color=(255, 0, 0, 255),
)
label.draw()
arr = None
...

please try this code:
import pyglet
from gym.envs.classic_control import rendering
class DrawText:
def __init__(self, label:pyglet.text.Label):
self.label=label
def render(self):
self.label.draw()
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.add_geom(DrawText(label))
viewer.render(return_rgb_array=False)
input()

Related

How to get bounding box with text using Tesseract4Android?

I am using 'cz.adaptech.tesseract4android:tesseract4android:4.3.0' in my Android project.
Is it possible to get bounding box with text data like in example below?
(32, 24, 60, 17) Maitre
(100, 24, 82, 19) corbeau,
(191, 28, 29, 13) sur
(227, 28, 22, 12) un
(257, 24, 50, 17) arbre
(315, 24, 70, 21) perché,
(79, 49, 58, 17) Tenait
Official sample shows how to get plain text only, not boxes with text inside:
TessBaseAPI tess = getTessBaseAPI(path, context);
String text = tess.getUTF8Text();
To get bounding box with text use next code:
TessBaseAPI tess = new TessBaseAPI();
// Given path must contain subdirectory `tessdata` where are `*.traineddata` language files
String dataPath = context.getExternalFilesDir(null).getPath() + "/OCRme/";
// Initialize API for specified language (can be called multiple times during Tesseract lifetime)
if (!tess.init(dataPath, "eng", TessBaseAPI.OEM_TESSERACT_LSTM_COMBINED)) {
throw new IOException("Error initializing Tesseract (wrong data path or language)");
}
// Specify image and then recognize it and get result (can be called multiple times during Tesseract lifetime)
tess.setImage(bitmap);
tess.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO_OSD);
tess.getUTF8Text();
ResultIterator resultIterator = tess.getResultIterator();
List < Rect > boxes = new ArrayList < > ();
List < String > texts = new ArrayList < > ();
while (resultIterator.next(TessBaseAPI.PageIteratorLevel.RIL_WORD)) {
Rect rect = resultIterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_WORD);
String text = resultIterator.getUTF8Text(TessBaseAPI.PageIteratorLevel.RIL_WORD);
boxes.add(rect);
texts.add(text);
}

How do I Update on Qwidget?

I wanna create a QWidget with 2 button and 1 label where this widget will be connected with a database in PYQT6. Now 1st button will move to previous data and 2nd button will move to next data and in the label I'll show the save image in that particular img save in that selected column of that database. I created a dbms and also create my desire widget but now I can't connecting the buttons and the dbms. Here the code I
progress.
import mysql.connector as mc
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(511, 447)
self.label_3 = QtWidgets.QLabel(parent=Form)
self.label_3.setGeometry(QtCore.QRect(110, 100, 281, 241))
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.previous = QtWidgets.QPushButton(parent=Form)
self.previous.setGeometry(QtCore.QRect(20, 380, 111, 31))
self.previous.setObjectName("previous")
self.next = QtWidgets.QPushButton(parent=Form)
self.next.setGeometry(QtCore.QRect(374, 380, 111, 31))
self.next.setObjectName("next")
self.widget = QtWidgets.QWidget(parent=Form)
self.widget.setGeometry(QtCore.QRect(30, 40, 188, 22))
self.widget.setObjectName("widget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.point1 = QtWidgets.QLabel(parent=self.widget)
self.point1.setObjectName("point1")
self.horizontalLayout.addWidget(self.point1)
self.lineEdit = QtWidgets.QLineEdit(parent=self.widget)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout.addWidget(self.lineEdit)
self.widget1 = QtWidgets.QWidget(parent=Form)
self.widget1.setGeometry(QtCore.QRect(290, 40, 188, 22))
self.widget1.setObjectName("widget1")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget1)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.point2 = QtWidgets.QLabel(parent=self.widget1)
self.point2.setObjectName("point2")
self.horizontalLayout_2.addWidget(self.point2)
self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.widget1)
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout_2.addWidget(self.lineEdit_2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def select_current(self):
self.rowcount = self.setRowCount(1)
self.colcount = self.setColCount(1)
def check_database(self):
try:
self.mydb = mc.connect(
host="localhost",
user="root",
password="",
database="dataimage"
)
self.tablename = "users"
mycursor = mydb.cursor()
except mc.Error as e:
self.label_3.setText("Error found")
def move_previous(self):
cursor = mydb.cursor
cursor.execute("SELECT Xpoint FROM {}".format(tablename))
self.result= self.mycursor.fetchall()
print(self.colcount.Xpoint)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.previous.setText(_translate("Form", "Previous"))
self.next.setText(_translate("Form", "Next"))
self.point1.setText(_translate("Form", "X_Point"))
self.point2.setText(_translate("Form", "Y_Point"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec())
Expecting that my button will move base on my data on database and will show the save img on that data on that col.

wxPython popup / tooltip on a wx.DrawRectangle?

In the code below, DrawRect1 and DrawRect2 represent a simplified version of functions that draw multiple shapes on screen.
I want to display some supplementary information if I hover over any of the drawn rectangles (similar to the way a tooltip works). But I need to generate that display information from a function rather than static definition.
Given I know the coords of the draw rectangle, can I either create another type of object with the same coords, or link a hover action to each drawnrectangle, so that I could call a function defined something like this ? :
EDIT: I guess I need a object I can bind a wx.EVT_ENTER_WINDOW event to, that I can create at the same time as dc.DrawRectangle ? Or can I bind this handler to the panel and use x,y position to try and match to a list of drawn rectangle coords ?
The closest thing I could find on SO was this old question, wxpython tooltip at specific coordinates but it wasn't a comprehensive answer.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 10, 100, 100)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()
A DC doesn't appear to support adding a tooltip, which is annoying, especially as the underlying wx widget appears to, as far as I can tell from the docs.
The best I can come up with at the moment, is to track the mouse movements but it is far from satisfactory and I suspect so limited that it might not be any help.
With those caveats made, I've supplied 3 options for the ToolTip like display. Namely, setting and unsetting the tooltip of the panel itself, a statusbar entry and a popup window.
Discard any you don't require.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.tips = ["","Rectangle 1","Rectangle 2"]
self.rect = []
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
self.status = self.CreateStatusBar()
self.status.SetFieldsCount(number=2)
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
self.panel.Bind(wx.EVT_MOTION, self.MouseMovement)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 20, 100, 200)
#Note the position of the DC
self.rect = [x for x in self.dc.BoundingBox]
#Append the id
self.rect.append(1)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
self.rect = [x for x in self.dc.BoundingBox]
self.rect.append(2)
def MouseMovement(self, event):
x,y = event.GetPosition()
self.panel.SetToolTip('')
self.status.SetStatusText('', 1)
if self.rect:
if x >= self.rect[0] and x <= self.rect[2] and y >= self.rect[1] and y <= self.rect[3]:
self.panel.SetToolTip(self.tips[self.rect[4]])
self.status.SetStatusText("Hovering over "+self.tips[self.rect[4]], 1)
win = Popup(self,self.rect[4],self.tips[self.rect[4]])
pos = self.GetScreenPosition()
win.Position(pos,(-1,-1))
win.Popup()
class Popup(wx.PopupTransientWindow):
def __init__(self, parent, id, id_text):
wx.PopupTransientWindow.__init__(self, parent)
panel = wx.Panel(self)
panel.SetBackgroundColour("gold")
text = wx.StaticText(panel, -1,
"This is a wx.PopupTransientWindow\n"
"Click mouse outside of it\n\n"
"Id of widget is "+str(id)+"\n"
"You are hovering over "+id_text)
# add other widgets here if required
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.ALL, 5)
panel.SetSizer(sizer)
sizer.Fit(panel)
sizer.Fit(self)
self.Layout()
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()

Is there any way to vertically-align iText (iTextSharp) text using ColumnText?

Is there any way to vertically-align text using ColumnText? I am using iTextSharp
Chunk c = new Chunk(text, this.detailFont);
Phrase myText = new Phrase(c);
ct.SetSimpleColumn(myText, llx, lly, urx, ury, lineheight, Element.ALIGN_BOTTOM);
ct.Go();
My text appears at the top of the box I specify. I would like it to align with the bottom of the box.
as it is as it should be
|---------------| |---------------|
| some text | ---> | |
| | | some text |
|---------------| |---------------|
The answer of birwin is just not working. The ColumnText alignment is accept only horizontal alignments. And this is working till ColumnText text is in Text mode. When you call the ColumnText.AddElement the ColumnText switches to CompositMode and the Alignment has no effect.
If you really want to Vertical Alignment in ColumnText then you have to create a content which has aligned content and must add to ColumnText. Only the Table and Cell the correct object where vertical alignment has any effect.
So first we have to create a table, with one column and one cell. And set the size of the cell to same as column text size.
And second, this table must be added to ColumntText
Here is my code:
// create doc
var pdfDoc = new Document( PageSize.A4 );
var pdfWriter = PdfWriter.GetInstance( pdfDoc, new FileStream( Path.Combine( Path.GetTempPath(), "test.pdf" ), FileMode.Create ) );
pdfDoc.Open();
var canvas = pdfWriter.DirectContent;
canvas.SaveState();
canvas.Rectangle( 100, 100, 100, 100 );
canvas.SetRgbColorFill( 255, 128, 128 );
canvas.Fill();
canvas.RestoreState();
// create font
BaseFont bfTimes = BaseFont.CreateFont( BaseFont.TIMES_ROMAN, BaseFont.CP1252, false );
Font times = new Font( bfTimes, (float)10, Font.ITALIC, new BaseColor( (int)232434 ) );
Phrase myText = new Phrase( new Chunk( "Hello World", times ) );
ColumnText ct = new ColumnText( canvas );
/* wrong birwin code :
ct.SetSimpleColumn( myText, 100, 100, 200, 200, ct.Leading, Element.ALIGN_BOTTOM );
*/
// new working code: crreate a table
PdfPTable table = new PdfPTable( 1 );
table.SetWidths( new[] { 1 } );
table.WidthPercentage = 100;
table.AddCell( new PdfPCell( myText )
{
HorizontalAlignment = Element.ALIGN_RIGHT,
VerticalAlignment = Element.ALIGN_BOTTOM,
FixedHeight = 100
} );
ct.SetSimpleColumn( 100, 100, 200, 200 );
ct.AddElement( table );
ct.Go();
pdfDoc.Close();
The Solution:
Chunk c = new Chunk(text, this.detailFont);
Phrase myText = new Phrase(c);
ct.SetSimpleColumn(myText, llx, lly, urx, ury, lineheight, Element.ALIGN_BOTTOM);
ct.Go(true);
if (ct.LinesWritten == 1)
{
ury = ury - (this.rowheight);
}
ct.SetSimpleColumn(myText, llx, lly, urx, ury, lineheight, Element.ALIGN_BOTTOM);
ct.Go();
ct.Go(true) -- Apparently the "true" here indicates the ColumnText is created in "Simulation" mode. I was not aware of this mode before comments to my question were posted.
if (ct.LinesWritten == 1) checks the number of lines that were written. If only one line was written, I shrink the size of the upper-right-y corner of my rectangle.
ct.SetSimpleColumn(myText, llx, lly, urx, ury, lineheight, Element.ALIGN_BOTTOM); when I call this line the second time, the ury (upper-right-hand corner) location has been changed and the box is smaller.
ct.Go() - The second time I call this, I don't pass the "true" param so the second call is not simulation mode and writes the data to the document.

Unusual Syntax Error in PyGame using Eclipse

import pygame
import time
import random
from __builtin__ import quit
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
ship_width = 73
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Galaxia Remastered')
clock = pygame.time.Clock()
background = pygame.image.load('space1.png')
background = pygame.transform.scale(background, (800,600))
shipImg = pygame.image.load('ship1.png')
shipImg = pygame.transform.scale(shipImg, (73,73))
mobImg = pygame.image.load('ufo.png')
mobImg = pygame.transform.scale(mobImg, (100,100))
def mobs_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, white)
gameDisplay.blit(text,(0,0))
def mobs(mobx, moby, mobw, mobh):
gameDisplay.blit(mobImg,(mobx,moby))
def ship(x,y):
gameDisplay.blit(shipImg,(x,y))
def text_objects(text,font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def message_display(text):
font = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text,font)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf,TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed!')
def button(msg,x,y,w,h,ic,ac):
mouse = pygame.mouse.get_pos()
if x + w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x,y,w,h))
else:
pygame.draw.rect(gameDisplay,ic, (x,y,w,h))
font = pygame.font.Font('freesansbold.ttf',20)
textSurf, textRect = text_objects(msg, font)
textRect.center = ((x+(w/2)),(y+(h/2))
gameDisplay.blit(textSurf, textRect)
The last line gives me an invalid syntax error, highlighting the "gameDisplay". After looking around myself, there was an "import gameDisplay from..." another file I had within the project. I thought that it would be fixed if I deleted the line, however it stated "unresolved import". I restarted Ecplise and cleaned my project multiple times but it still doesn't work. I sent the program to my other computer and it still gets the same error. When I remove the "gameDisplay" line, it tells me that there is an invalid syntax in "def game_intro():".
All help would be greatly appreciated.
It looks like you got one mismatched paranthese on line 74
Just remove the very first one on that line and your code should work just fine again..
textRect.center = (x+(w/2)),(y+(h/2))