1. 程式人生 > 其它 >[UG 二次開發 python] 生成略縮圖並儲存

[UG 二次開發 python] 生成略縮圖並儲存

儲存到零件同名的資料夾下,名稱相同,型別是 jpg

用到 numpy,PIL,cv2

blockstyler 檔案略

# nx: threaded
__version__ = "0.0.1"
__author__ = "unmht"
__blog__ = "https://www.cnblogs.com/unm001/"
from dlx.截圖製作 import 截圖製作 


import os
import NXOpen
import NXOpen.BlockStyler
import NXOpen.UF
import cv2
import numpy as np
from PIL import Image

from support import info

os.chdir(os.path.dirname(os.path.abspath(__file__)))


class myclass(截圖製作):
    dwa: NXOpen.BlockStyler.DrawingArea
    bt0: NXOpen.BlockStyler.Button
    bt1: NXOpen.BlockStyler.Button

    def __init__(self):
        super().__init__()

        self.work = self.theSession.Parts.Work
        self.partpath = self.work.FullPath
        self.dirpath = os.path.dirname(self.partpath)
        self.imgpath = os.path.join(self.dirpath, f"{self.work.Name}.jpg")
        self.readimgok = False
        self.tmpimg = os.path.join(self.dirpath, "_tmp.jpg")
        self.imgdata = None
        if os.path.exists(self.tmpimg):
            os.remove(self.tmpimg)

    def dialogShown_cb(self):
        try:
            if os.path.exists(self.imgpath):
                self.dwa.Image = self.imgpath
                self.readimgok = True
        except Exception as ex:
            self.theUI.NXMessageBox.Show(
                "Block Styler", NXOpen.NXMessageBox.DialogType.Error, str(ex)
            )

    def update_cb(self, block):
        try:
            if block == self.dwa:
                # ---- Enter your code here -----
                pass
            elif block == self.bt0:
                if self.imgdata is not None:
                    cv2.imencode(".jpg", self.imgdata)[1].tofile(self.imgpath)
            elif block == self.bt1:
                r = False
                try:
                    r = self.capture()
                except Exception as e:
                    info(e)
                if r:
                    self.dwa.Image = self.tmpimg
        except Exception as ex:
            # ---- Enter your exception handling code here -----
            self.theUI.NXMessageBox.Show(
                "Block Styler", NXOpen.NXMessageBox.DialogType.Error, str(ex)
            )

        return 0

    def capture(self):
        self.imgdata = None
        imgbuilder = self.theUI.CreateImageExportBuilder()

        imgbuilder.RegionMode = False

        imgbuilder.FileFormat = NXOpen.Gateway.ImageExportBuilder.FileFormats.Jpg

        imgbuilder.FileName = self.tmpimg
        imgbuilder.BackgroundOption = (
            NXOpen.Gateway.ImageExportBuilder.BackgroundOptions.CustomColor
        )
        imgbuilder.SetCustomBackgroundColor([1.0, 1.0, 1.0])

        imgbuilder.EnhanceEdges = True

        imgbuilder.Commit()

        imgbuilder.Destroy()
        if os.path.exists(self.tmpimg):
            img = Image.open(self.tmpimg)
            img.load()

            imgtmp = np.asanyarray(img)
            img.close()
            os.remove(self.tmpimg)
            imgtmp = cv2.cvtColor(imgtmp, cv2.COLOR_RGB2BGR)
            imggray = cv2.cvtColor(imgtmp, cv2.COLOR_BGR2GRAY)
            imggray = 255 - imggray
            cts, hirs = cv2.findContours(
                imggray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
            )
            ct = max(cts, key=cv2.contourArea)
            rct = cv2.boundingRect(ct)

            x, y, width, height = rct
            imgCut = imgtmp[y : y + height, x : x + width]
            h2 = int(max(width * 2 / 3, height) + 0.1) + 4
            if h2 % 2 == 1:
                h2 = h2 + 1
            if h2 % 4 != 0:
                h2 = h2 + 2
            w2 = int(h2 * 1.5)
            dw = int((w2 - width) / 2)
            dh = int((h2 - height) / 2)

            imgret = np.full((h2, w2, 3), 255).astype(np.uint8)
            # info([imgCut.shape, imgret.shape])
            imgret[dh : dh + height, dw : dw + width] = imgCut
            # info([width, height, w2, h2, dw, dh])
            imgret2 = cv2.resize(imgret, (320, 240))

            cv2.imencode(".jpg", imgret2)[1].tofile(self.tmpimg)
            self.imgdata = imgret2
            return True


def main():
    thecls: myclass
    try:
        thecls = myclass()
        #  The following method shows the dialog immediately
        thecls.Show()
    except Exception as ex:
        # ---- Enter your exception handling code here -----
        NXOpen.UI.GetUI().NXMessageBox.Show(
            "Block Styler", NXOpen.NXMessageBox.DialogType.Error, str(ex)
        )
    finally:
        try:
            if thecls != None:
                if os.path.exists(thecls.tmpimg):
                    os.remove(thecls.tmpimg)
            if thecls != None:
                thecls.Dispose()
            thecls = None
        except Exception as e:
            pass


if __name__ == "__main__":

    main()