1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| import cv2 as cv import numpy as np import sys from PyQt5.Qt import * class MyWediget(QWidget): def __init__(self): super().__init__() self.setWindowTitle("分割烟草") self.setWindowIcon(QIcon("2.jpg")) self.setFixedSize(800, 430) self.setup_ui() self.arg = "" def setup_ui(self): def test(): fd = QFileDialog(window, "选择一个文件", "../", "All(*.*);;Images(*.png *.jpg);;Python文件(*.py)") fd.move(200,0) fd.setLabelText(QFileDialog.FileName, "我的文件") fd.setLabelText(QFileDialog.Accept, "接受")
fd.setLabelText(QFileDialog.Reject, "拒绝") fd.setFileMode(QFileDialog.ExistingFiles) def path(val): inputPath.setText(val) self.segmentation(val) fd.fileSelected.connect(path) fd.open() inputPath = QLineEdit(self) inputPath.resize(300,30) btn = QPushButton(self) btn.setText("选择文件") def click(): btn.isDefault() if len(inputPath.text()) > 0: evt = QKeyEvent() if evt.modifiers() == Qt.EnterKeyGo: btn.pressed.connect(click) btn.move(300,0) btn.clicked.connect(test)
def segmentation(self,val): windows = QWidget(self) windows.resize(400,400) windows.move(0,30)
w2 = QWidget(self) w2.move(400,30) w2.resize(400,400)
self.arg = val inputPath = QLineEdit(self) inputPath.setText(self.arg)
src = cv.imread(self.arg) print(src.shape) w = int(src.shape[1]) h = int(src.shape[0])
if w>1000 or h>800: w = int(w/2) h = int(h/2) src = cv.resize(src, (w, h), interpolation=cv.INTER_CUBIC) r = cv.selectROI('Draw a rectangle', src, False)
roi = src[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])]
mask = np.zeros(src.shape[:2], dtype=np.uint8)
rect = (int(r[0]), int(r[1]), int(r[2]), int(r[3]))
bgdmodel = np.zeros((1, 65), np.float64) fgdmodel = np.zeros((1, 65), np.float64)
cv.grabCut(src, mask, rect, bgdmodel, fgdmodel, 11, mode=cv.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 1) + (mask == 3), 255, 0).astype('uint8')
print(mask2.shape)
result = cv.bitwise_and(src, src, mask=mask2) cv.imwrite('result.jpg', result) cv.imwrite('roi.jpg', roi)
print("over") w2.setStyleSheet("border-image:url(roi.jpg)") windows.setStyleSheet("border-image:url(result.jpg)")
w2.show() windows.show()
if __name__ == '__main__': app = QApplication(sys.argv) window = MyWediget() window.show() sys.exit(app.exec_())
|