使图像的某些区域可选
我在一个图像上画了一个网格,通过绘制均匀间隔的水平和垂直线来实现,现在我想让每个矩形的网格部分可以被 选择
。
换句话说,如果用户点击网格中的某个矩形,那么这个矩形就会被单独保存为一个新的图像。我尝试过使用 QRubberBand
。
但是我不知道怎么限制选择只在用户点击的那个特定部分。有没有办法用 PyQt 来实现这个?
这是我用来在图像上绘制网格的代码:
class imageSelector(QtGui.QWidget):
def __init__(self):
super(imageSelector,self).__init__()
self.initIS()
def initIS(self):
self.pixmap = self.createPixmap()
painter = QtGui.QPainter(self.pixmap)
pen = QtGui.QPen(QtCore.Qt.white, 0, QtCore.Qt.SolidLine)
painter.setPen(pen)
width = self.pixmap.width()
height = self.pixmap.height()
numLines = 6
numHorizontal = width//numLines
numVertical = height//numLines
painter.drawRect(0,0,height,width)
for x in range(numLines):
newH = x * numHorizontal
newV = x * numVertical
painter.drawLine(0+newH,0,0+newH,width)
painter.drawLine(0,0+newV,height,0+newV)
label = QtGui.QLabel()
label.setPixmap(self.pixmap)
label.resize(label.sizeHint())
hbox = QtGui.QHBoxLayout()
hbox.addWidget(label)
self.setLayout(hbox)
self.show()
def createPixmap(self):
pixmap = QtGui.QPixmap("CT1.png").scaledToHeight(500)
return pixmap
def main():
app = QtGui.QApplication(sys.argv)
Im = imageSelector()
sys.exit(app.exec_())
if __name__== '__main__':
main()
1 个回答
0
扩展你的 QWidget
类,重写 mousePressEvent
方法,然后根据鼠标的实际位置找到对应的图块,并存储你想要保存的那部分图像。只需在你的类中添加以下方法,并填写具体的代码来处理图像的裁剪和存储。
def mousePressEvent(event):
"""
User has clicked inside the widget
"""
# get mouse position
x = event.x()
y = event.y()
# find coordinates of grid rectangle in your grid
# copy and store this grid rectangle
如果你想的话,还可以显示一个矩形的橡皮筋效果,让它在不同的矩形之间跳动。为此,你需要重写 mouseMoveEvent
方法。
def mouseMoveEvent(event):
"""
Mouse is moved inside the widget
"""
# get mouse position
x = event.x()
y = event.y()
# find coordinates of grid rectangle in your grid
# move rectangular rubber band to this grid rectangle