U
U
userpyy2020-08-20 19:30:38
Python
userpyy, 2020-08-20 19:30:38

How to make a transparent window in opencv?

I need to make it so that I can only draw the rectangle, while everything else is completely transparent - really transparent.

Here is the code:

while True:
    img = p_out.recv()

    for (x,y,w,h) in t1.detectMultiScale(img, ais, ain):
        p_in2.send(np.asarray([x,y,w,h]))
        cv2.rectangle(img, (x, y),(x+w, y+h), (0, 0, 255), 2)

    cv2.imshow("Vision", img)
    if cv2.waitKey(1) & 0 == 1:
        break

ps Do not look at how I get img, it's just an attempt to make the background transparent.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-08-21
@userpyy

As an option

import sys
import numpy
import cv2
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPixmap, QPalette, QBrush, QImage
from PIL import Image, ImageDraw, ImageQt


# Отловить ошибки в слотах PyQt5
def log_uncaught_exceptions(ex_cls, ex, tb):
    text = '{}: {}:\n'.format(ex_cls.__name__, ex)
    import traceback
    text += ''.join(traceback.format_tb(tb))

    print(text)
    QMessageBox.critical(None, 'Error', text)
    quit()
sys.excepthook = log_uncaught_exceptions


class TransparentWindow(QWidget):
  def __init__(self):
    super().__init__()
    self.interface()
  def interface(self):
    self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
    self.setWindowFlag(Qt.WindowStaysOnTopHint)

    pil_image = Image.new('RGBA', (300, 300), (0, 0, 0, 0))
    draw = ImageDraw.Draw(pil_image)
    draw.rectangle((0, 0, 300, 300), outline=(0, 0, 255), width=5)

    numpy_array = numpy.array(pil_image)
    opencv_image = cv2.cvtColor(numpy_array, cv2.COLOR_RGBA2BGRA)# cv2.COLOR_BGR2HSV

    # Start coordinate, here (5, 5)
    # represents the top left corner of rectangle
    start_point = (5, 5)

    # Ending coordinate, here (220, 220)
    # represents the bottom right corner of rectangle
    end_point = (220, 220)

    # Blue color in BGRA
    color = (0, 0, 255, 255)

    # Line thickness of 2 px
    thickness = 2

    # Using cv2.rectangle() method
    # Draw a rectangle with blue line borders of thickness of 2 px
    image = cv2.rectangle(opencv_image, start_point, end_point, color, thickness)


    # Конвертируем изображение из OpenCV в PIL
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA))

    image_qt = ImageQt.toqimage(pil_image)

    pixmap = QPixmap.fromImage(image_qt)

    palette = self.palette()
    palette.setBrush(QPalette.Normal, QPalette.Window, QBrush(pixmap))
    palette.setBrush(QPalette.Inactive, QPalette.Window, QBrush(pixmap))

    self.setPalette(palette)
    self.setMask(pixmap.mask())

  def drag_window(self, event):
    delta = QPoint(event.globalPos() - self.old_position)
    self.move(self.x() + delta.x(), self.y() + delta.y())
    self.old_position = event.globalPos()
  def mousePressEvent(self, event):
    """Выбрать окно при помощи мыши"""
    self.old_position = event.globalPos()
    self.old_position = event.globalPos()
  def mouseMoveEvent(self, event):
    """Переместить окно с помощью мыши"""
    self.drag_window(event)
    x, y = self.get_window_coordinates()
    width, height = self.get_window_size()
    region = x, y, width, height
  def get_window_size(self):
    """Вернёт кортеж(width, height) размер окна"""
    size = self.frameSize().width(), self.frameSize().height()
    return size
  def get_window_coordinates(self):
    """Вернёт кортеж(x, y) координаты окна"""
    coordinates = self.x(), self.y()
    return coordinates


def main():
    application = QApplication(sys.argv)
    transparent_window = TransparentWindow()
    transparent_window.show()
    sys.exit(application.exec_())

if __name__ == '__main__':
    main()

A
AlexBoss, 2020-08-20
@AlexBoss

Why do you need a transparent background if you can only display this image?
proc_img= img[y:y+h, x:x+w]
PS can you add something to the background

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question